首页 > 解决方案 > 如何捕获在 c# 上的 c++ dll 中生成的自定义异常?

问题描述

我正在创建一个用于 C# 的 C++ DLL。每当出现任何错误时,此 DLL 都会引发异常,其想法是在 C# 代码中处理这些异常。

我在继承自的 C++ 中创建了一个新的异常类,std::runtime_error因为我不仅需要what数字 ID,还需要一个数字 ID:

class insight_exception: public std::runtime_error
{
public:
    explicit insight_exception(const int id, const std::string message):
    std::runtime_error(message), id{id}
    {}

    virtual ~insight_exception() noexcept {}

    const int id;
};

每当 C++ 代码出现问题时,我都会这样做:

throw insight_exception(103, "size Pointer is NULL");

我在 C# 中有一个小例子来“练习”DLL,只是在将它发送给我们的 C# 开发人员之前对其进行测试,当我执行这个小 C# 程序时,我可以验证 DLL 是否抛出异常,因为我得到了这个:

terminate called after throwing an instance of 'insight_exception'

我的问题是我不知道任何 C# 并且我真的不知道将insight_exception类“导入”到 C# 中以便我可以抓住它。

这篇文章这样的解决方案没有帮助,因为它们假设您可以通过使用如下函数来使用该类:

insight_exception* create_insight_exception()
{
    return new insight_exception();
}

我不能这样做,因为我在 C# 中需要这样的东西

try
{
}
catch (insight_exception e)
{
}

所以我不能像这样创建类:

IntPtr insight_exception = create_insight_exception();

要知道的一件重要事情是,我正在通过使用 MinGW 交叉编译在 Linux 上创建 DLL,因此在创建 DLL 时我不能执行#include <Windows.h>任何其他与 Windows 相关的包含或导入。我并不真正使用 Windows,但仅用于我的小测试 C# 代码。


编辑:

感谢评论,我调查了以下问题:

C# 没有从非托管 C++ dll 中捕获未处理的异常

这个看起来很有希望,但问题是答案建议在 Windows 中完成编译。我尝试/EHa在 GCC (-funwind-tables) 中添加等效的编译标志,但这无济于事。我仍然无法在 C# 代码中使用catch (SEHException ex)nor捕获异常。catch (Exception ex)


您可以在 C# 代码中捕获本机异常吗?

建议使用Win32Exception,但这也不起作用。我无法catch (Win32Exception ex)在 C# 代码中捕获异常。

标签: c#c++exceptiontry-catch

解决方案


推荐阅读