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

后端 未结 2 1406
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 04:12

The C++ function definition is this

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

And I call it in C# like this

相关标签:
2条回答
  • 2021-01-15 04:20

    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.

    0 讨论(0)
  • 2021-01-15 04:23

    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);
    
    0 讨论(0)
提交回复
热议问题