2013-07-29 36 views
1

如何將C中的基於char**的數組轉換爲C#中的等效類型?如何將基於char **的數組從基於C的dll轉換爲c#等價物?

我有一個函數,它需要一個char**緩衝區並用正確的數據填充它的DLL。

我使用的是C#應用程序中該DLL使用DllImport

,當我需要指定return typeargument type這種功能的問題開始。

C#中的哪一個類型等價於C char**數組?

我應該做什麼和什麼?

更新
這是位於我的DLL裏面我的C函數:

CDLL_API wchar_t** GetResults(wchar_t* word, int* length, int threshold = 9); 

而這兩個函數調用下面的函數來獲得自己的價值:

wchar_t** xGramManipulator::CGetNextWordsList(const wchar_t* currentWord, int threshold) 
{ 
    wstring str(currentWord); 
    auto result = GetNextWordsList(str, threshold); 

    return GetCConvertedString(result); 
} 

wchar_t ** xGramManipulator::GetCConvertedString(vector< wstring> const &input) 
{ 
    DisposeBuffers();//deallocates the previously allocated cStringArrayBuffer. 
    cStringArraybuffer = new wchar_t*[input.size()]; 
    for (int i = 0; i < input.size(); i++) 
    { 
     cStringArraybuffer[i] = new wchar_t[input[i].size()+1]; 
     wcscpy_s(cStringArraybuffer[i], input[i].size() + 1, input[i].c_str()); 
     cStringArraySize++; 
    } 
    return cStringArraybuffer; 
} 

我用wchar_T **,但我認爲不應該有任何區別C#方面(因爲c#默認支持unicode!所以如果它的不同請寄給我)

+0

您是否嘗試過使用ref字符串? –

+0

'string []'should work afaik – x4rf41

+0

不,我完全不知道它。 – Breeze

回答

3

在評論你的狀態,你最感興趣的是處理這個功能:

CDLL_API wchar_t** GetResults(wchar_t* word, int threshold); 

你不能指望的P/Invoke編組編組的返回值給你。你需要手動完成。而且,您無法可靠地調用當前設計的功能。這是因爲調用者沒有辦法獲得返回數組的長度。你將需要添加一個額外的參數數組長度返回給調用者:

CDLL_API wchar_t** GetResults(wchar_t* word, int threshold, int* len); 

在C#側你聲明它是這樣的:

[DllImport(@"DllName.dll", CallingConvention=CallingConvention.Cdecl)] 
static extern IntPtr GetResults(
    [MarshalAs(UnmanagedType.LPWStr)] 
    string word, 
    int threshold, 
    out int len 
); 

而且你需要請確保您在DllImport中指定的調用約定與本機代碼的調用約定相匹配。我假設cdecl,但只有你知道肯定。

這樣稱呼它:

int len; 
IntPtr results = GetResults(word, threshold, out len); 
IntPtr[] ptrs = new IntPtr[len]; 
Marshal.Copy(results, ptrs, 0, len); 
for (int i=0; i<len; i++) 
{ 
    string item = Marshal.PtrToStringUni(ptrs[i]); 
} 

爲了避免內存泄漏,您需要導出取消分配由GetResults分配的內存的另一個功能。打完電話後請致電PtrToStringUni

非常坦率地說,這看起來非常適合混合模式的C++/CLI解決方案。

+0

謝謝,我會試一試,如果我遇到任何問題,我會評論。再次感謝所有的事情:) – Breeze

+0

有幾個錯誤在這裏: http://pastebin.com/mPQdXzMm – Breeze

+1

@Hossein是的,傻我,應該是'IntPtr [] ptrs',根據最新更新 –

相關問題