How to import const char* API to C#?

廉价感情. 提交于 2019-12-18 13:25:50

问题


Given this C API declaration how would it be imported to C#?

const char* _stdcall z4LLkGetKeySTD(void);

I've been able to get this far:

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

回答1:


Try this

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

You can then convert the result to a String by using Marshal.PtrToStringAnsi(). You will still need to free the memory for the IntPtr using the appropriate Marshal.Free* method.




回答2:


Always use C++ const char* or char* and not std::string.

Also keep in mind that char in C++ is a sbyte in C# and unsigned char is a byte in C#.

It is advisable to use unsafe code when dealing with 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());
 }



回答3:


Just use 'string' instead of 'const char *'.

Edit: This is dangerous for the reason JaredPar explained. If you don't want a free, don't use this method.



来源:https://stackoverflow.com/questions/508227/how-to-import-const-char-api-to-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!