如何在 C# 应用程序中使用 extern "C" dll 函数以 char** 作为参数?
How to use extern "C" dll function taking char** as an argument in C# application?
我有带功能的dll
extern "C"
int
doJob(char** buffer);
它在C++中的用法如下:
char* buf;
int status = doJob(&buf);
在C#中,我应该对这个函数有什么定义?如何在C#中使用此函数?
可能的模式之一是:
[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端,您可以使用两个可以释放的分配器之一: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
相关文章:
- 将char*传递给pthread_read函数
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 将函数参数"const char*"转换为"std::string_view"是
- std::string 构造函数如何处理固定大小的 char[]?
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 构造函数 (C++) 中的 char 指针参数存在问题
- c ++ 如何在构造函数中初始化 char
- C++ 存储来自 char* 函数的字符列表
- 从循环返回char函数数据
- 预处理器检查 constexpr const char* 函数
- 如何使const char*函数起作用
- 返回一个带有随机选项和局部变量的 char 函数
- System::字符串到char*函数.内存泄漏
- 如何在c++中使用递归char *函数来反转字符串
- 如何在c++中创建一个char函数
- Windows与UTF-16一起使用char*函数
- c++在char函数中搜索char