简体   繁体   English

在C#中捕获本机C ++异常

[英]Catching native C++ exceptions in C#

I have some native C++ class libraries that I have wrapped up in C++ .NET which I then call from C# (three layers!). 我有一些本机C ++类库,我已经用C ++ .NET包装了,然后我从C#调用(三层!)。

I can throw exceptions from C++ .NET and happily catch them in C#. 我可以从C ++ .NET中抛出异常,并愉快地在C#中捕获它们。 The trouble is that the only way I can catch my native C++ exceptions is by catching System.Exception, which is fine but in the conversion from std::exception to System.Exception I lose the vast majority of the information about the error (for example the error message!). 麻烦的是,我能捕获我的本机C ++异常的唯一方法是捕获System.Exception,这很好但是在从std :: exception到System.Exception的转换中我丢失了大部分关于错误的信息(对于示例错误消息!)。 I can catch the native exception in the C++ .NET layer and rethrow as a .NET exception but this is an intrusive solution that requires me to place try-catch blocks (to catch the native exceptions and rethrow) around every C++ .NET method call. 我可以捕获C ++ .NET层中的本机异常并重新抛出.NET异常,但这是一个侵入式解决方案,需要我在每个C ++ .NET方法调用周围放置try-catch块(以捕获本机异常和重新抛出) 。

Is there an alternative solution to doing this or am I just going to have to get my hands dirty ... 是否有替代解决方案,或者我只是要弄脏手...

You are going to have to get your hands dirty, but you can reduce the work a lot by creating a preprocessor macro to encapsulate all the repeated catch logic. 您将不得不弄脏自己,但是通过创建预处理器宏来封装所有重复的catch逻辑,您可以大大减少工作量。

I am assuming you will want to catch several different types of exception, eg MFC CException, std::exception, as well as SEH exceptions. 我假设你想要捕获几种不同类型的异常,例如MFC CException,std :: exception,以及SEH异常。

You might also want to write your wrapper functions to return HRESULTS and use SetErrorInfo (ie convert to COM error codes and error information) - you may decide this gives a cleaner interface to .Net which can convert this nicely to .Net exceptions. 可能还想编写包装函数以返回HRESULTS并使用SetErrorInfo(即转换为COM错误代码和错误信息) - 您可能会认为这为.Net提供了一个更清晰的界面,可以很好地将其转换为.Net异常。 This would avoid the need for a C++.Net layer and allow you to use P/Invoke, as well as making it callable from VBA. 这样可以避免使用C ++ .Net层,并允许您使用P / Invoke,以及使其可以从VBA调用。

Or you might not... just pointing out the option! 或者你可能不会......只是指出选项!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM