在使用 pinvoke 并在 linux 上运行的 dotnet 核心应用程序中,当 c++ 抛出 - 例如 - std::runtime_error
- 我们得到:
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 block 中。
如何在 dotnet 核心托管代码中捕获和处理它?
最佳答案
我设置了this Minimal, Complete and Verifiable example这演示了如何在 Linux 上通过托管 C# .NET Core 代码不捕获任何 native 异常。
如 the issue I opened for dotnet/coreclr
中所述, 我已经尝试了武器库中的 (m) 种可能的武器,但无济于事。
dotnet 团队给出的直接答案是:
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.
同样被dotnet团队推荐的Mono项目的解决方案是:
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.
这就是我们最终实现的,嗯,它有效:)。
关于c# - 在 dotnet 核心中捕获 native 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851329/