boost :: python导出自定义异常并继承自Python的Exception [英] boost::python export custom exception and inherit from Python's Exception
问题描述
boost :: python导出自定义异常的可接受答案显示了如何导出自定义C ++中的异常类,以及 Boost.Python自定义异常类显示了如何导出异常从Python的Exception继承的类.我该怎么办?这暴露了一个异常类,该异常类具有用于检索信息的自定义方法,并且该类也从Python的Exception派生.
The accepted answer to boost::python Export Custom Exception shows how to export a custom exception class from C++, and Boost.Python custom exception class shows how to export an exception class that inherits from Python's Exception. How can I do both? That is expose an exception class that has custom methods to retrieve information and also have that class be derived from Python's Exception.
推荐答案
Jim Bosch在 C ++信号列表,是使用合成,而不是从包装的C ++异常继承.代码必须像此处一样创建Python异常,然后添加包装的C ++作为Python异常的实例变量.
A workable solution, suggested by Jim Bosch on the C++-sig list, is to use composition instead of inheriting from the wrapped C++ exception. The code must create a Python exception as is done here, and then add the wrapped C++ exception as an instance variable of the Python exception.
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 ++异常:
The wrapped C++ exception can then be accessed from Python like this:
try:
...
except MyModule.MyCPPExceptionType as e:
cause = e.cause # wrapped exception can be accessed here
但该异常也会被
try:
...
except Exception:
...
这篇关于boost :: python导出自定义异常并继承自Python的Exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!