How to import const char * API in C #?

Given this C API API declaration, how will it be imported into C #?

const char* _stdcall z4LLkGetKeySTD(void); 

I managed to get this far:

  [DllImport("zip4_w32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "z4LLkGetKeySTD", ExactSpelling = false)] private extern static const char* z4LLkGetKeySTD(); 
+7
c # dllimport
source share
3 answers

try it

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

Then you can convert the result to a string using Marshal.PtrToStringAnsi (). You still need to free memory for IntPtr using the appropriate Marshal.Free * method.

+12
source share

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

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

It is advisable to use unsafe code when working 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()); } 
+4
source share

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

Edit: This is dangerous for the reason explained by JaredPar. If you do not want free, do not use this method.

+2
source share

All Articles