cha*_*ase 4 c++ python swig exception
我正在使用 swig 用 python 包装 C++ 库中的类。它总体上工作正常,但是有一个从库内部抛出的异常,我似乎无法在 swig 界面中捕获它,所以它只会使 python 应用程序崩溃!
PyMonitor.cc 类描述了所需类 Monitor 的 swig 接口。如果连接失败,监视器的构造函数将引发异常。我想在 PyMonitor 中处理这个异常,例如:
PyMonitor.cc:
#include "Monitor.h"
// ...
bool PyMonitor::connect() {
try {
_monitor = new Monitor(_host, _calibration);
} catch (...) {
printf("oops!\n");
}
}
// ...
Run Code Online (Sandbox Code Playgroud)
但是, connect() 方法永远不会捕获异常,我只是收到“抛出...后终止调用”错误,并且程序中止。
我对 swig 不太了解,但在我看来,这都是很好的 C++,并且异常应该在终止程序之前传播到 connect() 方法。
有什么想法吗?
如果您想在 Python 中解析异常,则必须将其转发给 Python。请参阅SWIG 文档。为了转发异常,您只需在 SWIG 接口 (.i) 文件中添加一些代码。基本上,它可以位于 .i 文件中的任何位置。
应在此处指定所有类型的异常,并且 SWIG仅捕获列出的异常类型(在本例中为 std::runtime_error、std::invalid_argument、std::out_of_range),所有其他异常均作为未知异常捕获(并因此被转发)正确!)。
// Handle standard exceptions.
// NOTE: needs to be before the %import!
%include "exception.i"
%exception
{
try
{
$action
}
catch (const std::runtime_error& e) {
SWIG_exception(SWIG_RuntimeError, e.what());
}
catch (const std::invalid_argument& e) {
SWIG_exception(SWIG_ValueError, e.what());
}
catch (const std::out_of_range& e) {
SWIG_exception(SWIG_IndexError, e.what());
}
catch (...) {
SWIG_exception(SWIG_RuntimeError, "unknown exception");
}
}
Run Code Online (Sandbox Code Playgroud)