in a dotnet core application that uses pinvoke and runs on linux, when c++ throws - for example - std::runtime_error
- we get:
terminate called recursively
terminate called after throwing an instance of 'terminate called after throwing an instance of 'std::runtime_error*'
Aborted (core dumped)
even though the invocation of the externed c++ method is wrapped in a try catch block in the managed code.
how can this be caught and treated in the dotnet core managed code?
I set-up this Minimal, Complete and Verifiable example that demonstrates how native exceptions are NOT caught whatsoever by managed C# .NET Core code, on Linux.
As described in the issue I opened for dotnet/coreclr
, I've tried (m)any possible weapon(s) in the arsenal, to no avail.
The direct answer given by dotnet team was:
We do not support exception handling interop on Unix. There is no good way to do it. The Mono project has a great write up on it here: http://www.mono-project.com/docs/advanced/pinvoke/#runtime-exception-propagation . The same reasoning applies to .NET Core.
The Mono project's solution, which is also recommended by the dotnet team, is:
C++ exceptions will need to be mapped into an “out” parameter or a return value, so that managed code can know what error occurred, and (optionally) throw a managed exception to “propagate” the original C++ exception.
That's what we eneded up implementing and, well, it works :).