Bill Walton
Bill Walton

Reputation: 823

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

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.

Upvotes: 2

Views: 3278

Answers (2)

Lloyd
Lloyd

Reputation: 29668

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);

Upvotes: 5

Andre Loker
Andre Loker

Reputation: 8408

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.

Upvotes: 0

Related Questions