c# - 如何捕获在 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# 代码。
编辑:
感谢评论,我调查了以下问题:
这个看起来很有希望,但问题是答案建议在 Windows 中完成编译。我尝试/EHa
在 GCC (-funwind-tables) 中添加等效的编译标志,但这无济于事。我仍然无法在 C# 代码中使用catch (SEHException ex)
nor捕获异常。catch (Exception ex)
建议使用Win32Exception
,但这也不起作用。我无法catch (Win32Exception ex)
在 C# 代码中捕获异常。
解决方案
推荐阅读
- algorithm - 有多个嵌套for循环时如何找到时间复杂度
- python-3.x - 终端不起作用:它不再启动。如何解决?
- c# - 无效的列名 Entity Framework Core
- javascript - jQuery 方法无法将数据传递到 REST 服务器
- laravel - 即使在模型中使用 $guarded = [] 将值设置为可填充后,也会出现 MassAssignment 错误
- php - 是否可以为路由处理程序操作 beforeRoute() 中的参数数组?
- json.net - 使用模式提取部分 json 数据
- laravel - 产量不在laravel中显示内容
- testing - 无法从 proxyquire 返回新对象
- c# - 单元测试检查旧的编译,看不到代码的变化