问题
I have some native C++ class libraries that I have wrapped up in C++ .NET which I then call from C# (three layers!).
I can throw exceptions from C++ .NET and happily catch them in 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!). 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.
Is there an alternative solution to doing this or am I just going to have to get my hands dirty ...
回答1:
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.
I am assuming you will want to catch several different types of exception, e.g. MFC CException, std::exception, as well as SEH exceptions.
You might also want to write your wrapper functions to return HRESULTS and use SetErrorInfo (i.e. 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. 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.
Or you might not... just pointing out the option!
来源:https://stackoverflow.com/questions/11948651/catching-native-c-exceptions-in-c-sharp