Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

exception

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();
like image 431
Andreas Brinck Avatar asked Aug 20 '10 08:08

Andreas Brinck


1 Answers

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);
}
like image 151
Ove Avatar answered Oct 13 '22 04:10

Ove