从C ++ DLL处理用户定义的异常-.NET PInvoke/编组 [英] Handling user-defined exceptions from C++ DLL - .NET PInvoke/Marshalling

查看:71
本文介绍了从C ++ DLL处理用户定义的异常-.NET PInvoke/编组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究WPF应用程序,该应用程序内部使用PInvoke调用C/C ++ DLL.在DLL的调试模式下,每当发生错误时,该函数都会引发异常,该异常基本上是一种定义的结构,其中包含特定的错误消息和特定于模块的应用程序代码.这与正常的Win32错误日志记录不同.现在我的问题是我想捕获DLL引发的异常.

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.

如果在尝试使用Marshalled函数时,.NET会通知我说外部模块中发生了错误.

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);
}

现在,我了解C/C + = DLL异常不是从.NET的Exception类派生的类,因此.NET无法正确封送它.我无法将C ++ DLL更改为托管的DLL,也无法对dll代码进行任何源代码更改.

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.

我确实在MSDN上看到了类似的帖子,其中包含VC ++.NET中提供的解决方案,其中DLL的每个功能都被创建到包装器中,并引发从.NET类派生的异常.

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/zh-CN/csharpgeneral/thread/0624f3b3-5244-4cb8-be9c-29d464975d20

但是,这将需要另一个.net组装项目,该项目将在VC ++.NET中围绕200多个函数和结构创建包装器.现在,所有的DLL函数都已使用PInvoke导入到WPF应用程序中,因此,优先选择现有方案的任何附件.

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.

推荐答案

如果您要按照注释中的指示继续使用P/invoke,则唯一的选择是在DLL边界捕获异常.然后,您可以使用错误代码(而不是异常)将详细信息传递给托管应用程序.如果要使用P/invoke,则不能允许异常越过DLL边界.

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.

这篇关于从C ++ DLL处理用户定义的异常-.NET PInvoke/编组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆