开发者

How do I get a std::exception error description when calling a C++ dll from C# [duplicate]

开发者 https://www.devze.com 2023-01-12 14:57 出处:网络
This question already has answers here: Can you catch a native exception in C# code? (9 answers) 开发者_如何转开发
This question already has answers here: Can you catch a native exception in C# code? (9 answers) 开发者_如何转开发 Closed 6 years ago.

I have a C# application which calls a function in a C++ dll. This function can throw various exceptions which inherits std::exception. I currently catch these exceptions like this:

try
{
    //Call to C++ dll
}
catch (System.Exception exception)
{
    //Some error handling code
}

My first question is will this code catch all std::exception? My second question is how can I retrieve the std::exception::what string, if I examine exception.Message I only get "External component has thrown an exception".

EDIT: The function in question is in a non managed C++ dll, and imported like this in the C# class:

[DllImport("SomeDLL.dll")]
public extern static void SomeFunction();


The best way to go would be to handle the exception in C++, and save the error message somewhere. Then, in C# you can check if there was an error message saved, and if it was you can retrieve it.

C++:

try
{
    //do some processing
}
catch(std::exception& ex)
{
    // errorMessage can be a std::string
    errorMessage = ex.what();
}

C#:

[DllImport("SomeDLL.dll")]
public extern static void SomeFunction();
[DllImport("SomeDLL.dll")]
public extern static string GetError();

SomeFunction();
string Error = GetError();
if(String.IsNullOrEmpty(Error)==true)
{
    //The processing was successfull
}
else
{
    //The processing was unsuccessful
    MessageBox.Show(Error);
}


Call how? The CLR doesn't really "get" C++ exception handling. If you call the C++ code through COM, add a layer that catches the std::exception and wrap it with a HRESULT/IErrorInfo. If you call it through managed C++, add a layer that wraps it in a managed System.Exception etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消