Handling user-defined exceptions from C++ DLL - .NET PInvoke/Marshalling

限于喜欢 提交于 2019-12-13 19:11:47

问题


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.



来源:https://stackoverflow.com/questions/6753292/handling-user-defined-exceptions-from-c-dll-net-pinvoke-marshalling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!