I would like to make my extern C++ function return a message when an exception occurs. Something like this:
extern "C" __declspec(dllexport) const char* __stdcall Calculate(double &result, double a, double b)
{
try
{
result = InternalCalculation(a, b);
}
catch(std::invalid_argument& e)
{
return e.what();
}
return "";
}
double InternalCalculation(double a, double b)
{
if(a < b)
{
const char* err = "parameters error!";
throw std::invalid_argument(err);
}
return sqrt(a - b);
}
On the other hand, I call the function from my C# program and I would like to show error in a MessageBox
:
[DllImport(@"MyDll.dll", EntryPoint = "Calculate")]
private static extern IntPtr Calculate(out double result, double a, double b);
private void Calculate()
{
IntPtr err;
double result = 0;
err = Calculate(out result, out 2, out 3);
var sErr = Marshal.PtrToStringAnsi(err);
if (string.IsNullOrEmpty(sErr))
MessageBox.Show(sErr);
...
}
Unfortunately, it doesn't work.. the MessageBox
just shows random characters.
I'm surprised because if I replace:
return e.what();
by:
const char* err = "parameters error!";
return err;
Then "parameters error!" will be shown correctly in the messagebox of the C# code. Both err
and e.what()
are the same type (const char*
), so what's wrong with e.what()
??