boost::python Export Custom Exception的公认答案展示了如何从C++导出自定义异常类,Boost.Python custom exception class展示了如何导出继承自Python的异常类。我怎么才能同时做到这两点呢?也就是说,公开了一个异常类,该类具有检索信息自定义方法,并从Python的异常派生类。
发布于 2012-08-02 12:04:00
Jim Bosch在C++-sig list上建议的一个可行的解决方案是使用组合,而不是继承包装的C++异常。代码必须像here一样创建一个Python异常,然后添加包装的C++异常作为Python异常的实例变量。
void translator(const MyCPPException &x) {
bp::object exc(x); // wrap the C++ exception
bp::object exc_t(bp::handle<>(bp::borrowed(exceptionType)));
exc_t.attr("cause") = exc; // add the wrapped exception to the Python exception
PyErr_SetString(exceptionType, x.what());
}然后可以像这样从Python中访问包装的C++异常:
try:
...
except MyModule.MyCPPExceptionType as e:
cause = e.cause # wrapped exception can be accessed here但是异常也会被
try:
...
except Exception:
...https://stackoverflow.com/questions/11448735
复制相似问题