boost python的广义异常翻译

And*_*jos 8 c++ exception-handling boost-python

用于将特定C++异常转换为python的当前boost :: python示例如下所示:

void translate (const MyException& e) {
   PyErr_SetString(PyExc_RuntimeError, e.what());
}

boost::python::register_exception_translator<MyException>(translate);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这要求我们为每个异常编写一个特定的函数.我们试图通过编写通用异常转换器来简化这一过程:

#include <boost/python.hpp>

// Generalized exception translator for Boost Python
template <typename T> struct GeneralizedTranslator {

  public:

    void operator()(const T& cxx_except) const {
      PyErr_SetString(m_py_except, cxx_except.what());
    }

    GeneralizedTranslator(PyObject* py_except): m_py_except(py_except) {
      boost::python::register_exception_translator<T>(this);
    }

    GeneralizedTranslator(const GeneralizedTranslator& other): m_py_except(other.m_py_except) {
      //attention: do not re-register the translator!
    }

  private:

    PyObject* m_py_except;

};

//allows for a simple translation declaration, removes scope problem
template <typename T> void translate(PyObject* e) {
  ExceptionTranslator<T> my_translator(e);
}
Run Code Online (Sandbox Code Playgroud)

这段代码是否有效,您可以包含实现"what()"的异常,如下所示:

BOOST_PYTHON_MODULE(libtest)
{
  translate<std::out_of_range>(PyExc_RuntimeError);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,看起来boost :: python会将"翻译"代码称为"boost/python/detail/translate_exception.hpp"中的一个函数(第61行):

translate(e);
Run Code Online (Sandbox Code Playgroud)

在我们的通用异常处理程序中,这将是对GeneralizedTranslator :: operator()的调用,这对g ++不起作用,给出:

error: ‘translate’ cannot be used as a function
Run Code Online (Sandbox Code Playgroud)

有没有正确的方法来写这个?

int*_*jay 5

您将this指针作为translate函数传递,这会失败,因为指向对象的指针不能作为函数调用.如果你传递了*this它应该工作(请注意,这将复制构造GeneralizedTranslator对象).或者您可以将注册移出构造函数,然后调用

register_exception_translator<std::out_of_range>(GeneralizedTranslator<std::out_of_range>(PyExc_RuntimeError));
Run Code Online (Sandbox Code Playgroud)