2

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.

Bill Walton
  • 805
  • 1
  • 15
  • 31

2 Answers2

4

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);
Lloyd
  • 27,966
  • 4
  • 78
  • 91
  • Error 1 'System.Runtime.InteropServices.DllImportAttribute' does not contain a constructor that takes 2 arguments Program.cs 64 10 page :( – Gizmo Jan 10 '14 at 01:15
  • @Gizmo Good catch, missed out the property assignment, fixed now. – Lloyd Jan 10 '14 at 09:40
0

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.

Community
  • 1
  • 1
Andre Loker
  • 7,938
  • 1
  • 19
  • 35