问题描述
C++ 代码:
__declspec(dllexport) const char* Get() {
return "hello word!";
}
C# 代码:
[DllImport("TestLink.dll")]
public static extern string Get();
程序调用后直接崩溃
解决方法
无论如何,当你从 C/C++/Native 端分配一些东西时,你必须使用 .NET 理解的 COM 分配器。所以返回字符串的方式有很多种,例如:
C++:
extern "C" __declspec(dllexport) void* __stdcall GetBSTR() {
return SysAllocString(L"hello world"); // uses CoTaskMemAlloc underneath
}
extern "C" __declspec(dllexport) void* __stdcall GetLPSTR() {
const char* p = "hello world";
int size = lstrlenA(p) + 1;
void* lp = CoTaskMemAlloc(size);
if (lp)
{
CopyMemory(lp,p,size);
}
return lp;
}
extern "C" __declspec(dllexport) void* __stdcall GetLPWSTR() {
const wchar_t* p = L"hello world";
int size = (lstrlenW(p) + 1) * sizeof(wchar_t);
void* lp = CoTaskMemAlloc(size);
if (lp)
{
CopyMemory(lp,size);
}
return lp;
}
和 C#
[DllImport("MyDll")]
[return: MarshalAs(UnmanagedType.BStr)]
public static extern string GetBSTR();
[DllImport("MyDll")]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string GetLPWSTR();
[DllImport("MyDll")]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string GetLPSTR();