You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中正确调用带const char**参数的C++ DLL函数?

正确调用C++ DLL中带const char**参数的函数

你遇到的崩溃根源是C#封送器无法直接适配const char**到out string的转换——C++代码是直接给传入的指针赋值了静态字符串的地址,而默认的out string封送逻辑期望的是已分配好的缓冲区,两者不匹配导致内存访问错误。

正确的P/Invoke声明与调用

你需要用ref IntPtr对应C++的const char**,再手动将返回的指针转换为C#字符串:

[DllImport("SomeLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern ulong aFunction(ref IntPtr aStringPtr);

调用示例:

IntPtr stringPtr = IntPtr.Zero;
ulong result = aFunction(ref stringPtr);
string aString = Marshal.PtrToStringAnsi(stringPtr);
Text = aString;

方案说明

  • ref IntPtr直接对应C的const char**:IntPtr代表非托管指针,ref传递指针的地址,让C函数可以修改这个指针的值,指向它的静态字符串。
  • Marshal.PtrToStringAnsi负责将非托管ANSI字符串指针(const char*)转换为C#的string,内部会把字符串内容复制到托管内存,避免直接访问非托管静态内存的潜在风险。

额外注意

  • 由于C++返回的是静态字符串常量(存储在DLL的只读数据段),无需手动释放该指针,不会造成内存泄漏。
  • 如果C++函数返回的是动态分配的字符串(比如用malloc分配),则需要在C#中调用Marshal.FreeHGlobal释放对应内存,避免泄漏。

内容的提问来源于stack exchange,提问作者no one special

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:40:07