如何使用extern“C”dll函数将char **作为C#应用程序中的参数?

我有function的dll:

extern "C" int doJob(char** buffer); 

它在C ++中的用法如下所示:

 char* buf; int status = doJob(&buf); 

我应该在C#中为此函数定义什么? 如何在C#中使用此function?

其中一种可能的模式是:

 [DllImport("containsdojob.dll", CallingConvention = CallingConvention.Cdecl)] public static extern Int32 doJob(out IntPtr buffer); [DllImport("containsdojob.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void freeMemory(IntPtr buffer); 

 IntPtr buffer = IntPtr.Zero; string str = null; try { doJob(out buffer); if (buffer != IntPtr.Zero) { str = Marshal.PtrToStringAnsi(buffer); } } finally { if (buffer != IntPtr.Zero) { freeMemory(buffer); } } 

请注意,您需要一个freeMemory方法来释放doJob分配的内存。

还有其他可能的模式,例如基于BSTRSysAllocString ,更容易实现C#侧(但更难以实现C端)

使用BSTR的“模式”:

C面:

 char *str = "Foo"; // your string int len = strlen(str); int wslen = MultiByteToWideChar(CP_ACP, 0, str, len, 0, 0); BSTR bstr = SysAllocStringLen(NULL, wslen); MultiByteToWideChar(CP_ACP, 0, str, len, bstr, wslen); // bstr is the returned string 

C# – 侧:

 [DllImport("containsdojob.dll", CallingConvention = CallingConvention.Cdecl)] public static extern Int32 doJob([MarshalAs(UnmanagedType.BStr)] out string buffer); string str; doJob(out str); 

CLR自动处理(释放)内存。

如果您使用的是Visual C ++,甚至可以

 char *str = "Foo"; // your string _bstr_t bstrt(str); BSTR bstr = bstrt.Detach(); // bstr is the returned string 

或者在C端你可以使用两个可以释放的分配器之一C#-side: LocalAlloc或CoTaskMemAlloc :

 char *str = "Foo"; // your string char *buf = (char*)LocalAlloc(LMEM_FIXED, strlen(str) + 1); // or char *buf = (char*)CoTaskMemAlloc(strlen(str) + 1); strcpy(buf, str); // buf is the returned string 

然后你使用第一个例子,而不是调用

 freeMemory(buffer); 

你打电话:

 Marshal.FreeHGlobal(buffer); // for LocalAlloc 

要么

 Marshal.FreeCoTaskMem(buffer); // for CoTaskMemAlloc