Handling user-defined exceptions from C++ DLL - .N

2019-08-14 22:18发布

问题:

I am working on WPF application which internally calls a C/C++ DLL using PInvoke. In the debug mode of the DLL, whenever error occurs the function throw an exception which is basically a structure defined containing specific error message and application code specific to module. This is different from the normal Win32 error logging. Now my problem is I want to catch the exception thrown by the DLL.

If in use a try catch around the Marshalled function, .NET just informed me saying something wrong happened in the external module.

try
{
    // Marshalled function called
}
catch(Exception ex)
{
    MessageBox.show(ex.Message);
}

Now I understand the C/C+= DLL exception is not a class derived from Exception class of .NET hence .NET would not be able to marshal it properly. I cannot change the C++ DLL to managed one or make any source code changes to the dll code.

I did see a similar post on MSDN with the solution provided in VC++.NET where each function of DLL is created into a wrapper throwing an exception derived from .NET class.

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0624f3b3-5244-4cb8-be9c-29d464975d20

However, this would require another .net assembly project which would create wrappers around some 200 functions and structures in VC++.NET. Right now, all the DLL functions have been imported into WPF application using PInvoke so any add-on to existing scenario would be preferred.

回答1:

If you want to continue using P/invoke as you indicate in comments, then your only option is to catch the exceptions at the DLL boundary. You can then pass the details on to the managed application using error codes rather than exceptions. If you want to use P/invoke then you can't allow exceptions to cross the DLL boundary.