c# - 在 dotnet 核心中捕获 native 异常

标签 c# c++ .net-core interop pinvoke

在使用 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/

相关文章:

c# - 为什么在终结器中调用 Dispose() 会导致 ObjectDisposedException?

c# - 在WCF服务的内存中缓存明文密码

c++ - GCC 对 lambda 中的静态变量做了什么?

c++ - C++ 中 jasperreport 的替代品

asp.net-mvc - 在 ASP NET Core 中注册具有原始依赖项的类

c# - 如何去除多个 if-else 或重复的三元运算?

c# - 如果检查两者都有值并且相等,则简化

c# - MVC : no views found, 未搜索任何位置。为什么会这样?

c++ - 在 visual studio 中构建 fbxsdk 头文件时出现编译错误

c# - 仅适用于 Xamarin 的可移植类库吗?