Reputation: 823
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
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
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