在dotnet核心中捕获本机异常 [英] catch native exception in dotnet core
问题描述
在使用pinvoke并在linux上运行的dotnet核心应用程序中,当c ++抛出时-例如-std::runtime_error
-我们得到:
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)
即使外部c ++方法的调用被包装在托管代码中的try catch块中.
even though the invocation of the externed c++ method is wrapped in a try catch block in the managed code.
如何在dotnet核心托管代码中捕获并处理此问题?
how can this be caught and treated in the dotnet core managed code?
推荐答案
我设置了此最小,完整且可验证的示例,该示例演示在Linux上托管C#.NET Core代码如何不会捕获任何本机异常.
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.
如我为dotnet/coreclr
打开的问题所述,尝试在军械库中使用任何可能的武器,但无济于事.
As described in the issue I opened for dotnet/coreclr
, I've tried (m)any possible weapon(s) in the arsenal, to no avail.
dotnet团队给出的直接答案是:
The direct answer given by dotnet team was:
我们不支持Unix上的异常处理互操作.没有好的方法可以做到这一点. Mono项目在此处写得很棒: http ://www.mono-project.com/docs/advanced/pinvoke/#runtime-exception-propagation .相同的推理也适用于.NET Core.
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.
.net网络团队还推荐的Mono项目解决方案是:
The Mono project's solution, which is also recommended by the dotnet team, is:
C ++异常将需要映射到"out"参数或返回值中,以便托管代码可以知道发生了什么错误,并(可选)抛出托管异常以传播"原始C ++异常.
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 :).
这篇关于在dotnet核心中捕获本机异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!