boost::python export custom exception and inherit from Python's Exception

浪子不回头ぞ 提交于 2021-02-07 20:06:15

问题


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.


回答1:


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());
}

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

but the exception will also be caught by

try:
    ...
except Exception:
    ...


来源:https://stackoverflow.com/questions/11448735/boostpython-export-custom-exception-and-inherit-from-pythons-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!