2009-02-03 64 views
7

鑑於此C API聲明它將如何導入到C#?如何將const char * API導入C#?

const char* _stdcall z4LLkGetKeySTD(void); 

我已經能夠遠遠得到這個:

[DllImport("zip4_w32.dll", 
     CallingConvention = CallingConvention.StdCall, 
     EntryPoint = "z4LLkGetKeySTD", 
     ExactSpelling = false)] 
    private extern static const char* z4LLkGetKeySTD(); 

回答

12

試試這個

[DllImport("zip4_w32.dll", 
     CallingConvention = CallingConvention.StdCall, 
     EntryPoint = "z4LLkGetKeySTD", 
     ExactSpelling = false)] 
    private extern static IntPtr z4LLkGetKeySTD(); 

然後,您可以通過使用Marshal.PtrToStringAnsi結果轉換爲String()。您仍然需要使用適當的Marshal.Free *方法釋放IntPtr的內存。

2

只要使用的,而不是 '爲const char *' '串'。

編輯:這是JaredPar解釋的原因。如果你不想免費,不要使用這種方法。

+0

你把話說出我的嘴! – leppie 2009-02-03 18:06:58

+0

一定不要使用String。如果函數的返回值是一個字符串,則CLR將嘗試CoTaskMemFree這個可能不是用戶想要的原生指針 – JaredPar 2009-02-03 18:07:25

4

始終使用C++ const char *或char *而不是std :: string。

還請記住,C++中的字符是C#中的一個字節,並且無符號字符是C#中的一個字節。

建議在處理DllImport時使用不安全的代碼。

[DllImport("zip4_w32.dll", 
    CallingConvention = CallingConvention.StdCall, 
    EntryPoint = "z4LLkGetKeySTD", 
    ExactSpelling = false)] 
private extern static sbyte* or byte* z4LLkGetKeySTD(); 

void foo() 
{ 
    string res = new string(z4LLkGetKeySTD()); 
} 
相關問題