tags:

views:

1624

answers:

2

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  A: 

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.

Cody Brocious
You took the words out my mouth!
leppie
Definately don't use String. If the return of a function is a String the CLR will attempt to CoTaskMemFree the native pointer which is likely not what the user wants here
JaredPar
http://msdn.microsoft.com/en-us/magazine/cc164193.aspx bottom of the paragrah under figure 8
JaredPar
Wow, I had no idea about this. Answer and I'll be sure to vote you up!
Cody Brocious
+5  A: 

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.

JaredPar
How do you know which Marshal.Free* method should be used?
Mike Chess
@thelaughingdm, it depends on how the memory was allocated. The Marshal.FreeCoTaskMemAlloc frees a native CoTaskMemAlloc. Each one works with a particular native method
JaredPar