Catch unmanaged dll exception in .NET

Viewed 2530

I'm using an unmanaged DLL with a function that throws std::exception.

I'm using a .NET DLL wrapper so it can be distributed to use in .NET programs.

I would like to be able catch the message from the native exception but all I'm getting is System.Runtime.InteropServices.SEHException("External component has thrown an exception.")

Is there any way to propagate the exception details? Maybe I should export a custom exception from the native DLL? How would I do this?

Thanks

native DLL:

__declspec(dllexport) void __stdcall W32DLLFunc(int param) {
  if (param < 0) {
    throw new exception("Error: param must be > 0");
  }
  ...
}

.net DLL:

[DllImport("nw32.dll", CharSet = CharSet::Auto)]
static void W32DLLFunc(int param);

vb.net program:

Try
  W32DLLFunc(-1)
Catch ex As Exception
  MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
1 Answers
Related