如何使用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
分配的内存。
还有其他可能的模式,例如基于BSTR
和SysAllocString
,更容易实现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
要么
上述就是C#学习教程:如何使用extern“C”dll函数将char **作为C#应用程序中的参数?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
Marshal.FreeCoTaskMem(buffer); // for CoTaskMemAlloc
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1000680.html