Net5调用外部DLL方法,返回值为constchar*,C#将直接崩溃



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, p, 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();

最新更新