Is it possible to return a LPWSTR from C++ DLL to C# app

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 09:03:01

问题


The C++ function definition is this

__declspec(dllexport) LPWSTR __stdcall GetErrorString(int errCode);

And I call it in C# like this

 [DllImport("DLLTest.dll")]
 public static extern string GetErrorString(int errCode);

 static void Main(string[] args)
{
    string result = GetErrorString(5);
}

I get an unhandled exception of type System.Runtime.InteropServices.SEHException

I'm not even sure if it's ok for the C++ DLL to try to return a LPWSTR to C#...

Thanks.


回答1:


You might want to try something like this:

[DllImport("DLLTest.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string GetErrorString(int errCode);



回答2:


See the accepted answer here: PInvoke for C function that returns char *

The short version: you must marshal the return value as an IntPtr or the .NET runtime makes some assumptions and tries to delete the memory pointed to by the char pointer. This can cause crashes if the assumptions that the runtime makes are wrong.



来源:https://stackoverflow.com/questions/9516263/is-it-possible-to-return-a-lpwstr-from-c-dll-to-c-sharp-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!