【发布时间】:2021-04-14 00:20:39
【问题描述】:
C++ 代码:
__declspec(dllexport) const char* Get() {
return "hello word!";
}
C#代码:
[DllImport("TestLink.dll")]
public static extern string Get();
调用后程序直接崩溃
【问题讨论】:
-
但是使用IntPtr没有问题,我可以使用如下代码正常运行``` [DllImport("TestLink.dll")] public static extern IntPtr Get(); ```
-
我已经在 C++ 代码中看到了一个缺失的
__stdcall... 而且至少还有另一个问题... C# 将尝试释放 C++ 字符串的内存(必须分配由Marshal.AllocCoTaskMem而不一定是文字字符串)。您必须对 C# 说该字符串将是 ANSI 而不是 Unicode。到头来你走的是“正确”的相反方向。 -
内部不安全静态字符串 ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) { return null; } 返回新字符串((sbyte*)((void*)cstr));我可以使用上面的代码,我明白了。 NET框架好像是一样的转换
-
从 C++ 返回字符串的“经典”方式是使用
StringBuilder()C# 端。否则有各种解决方案