2011-08-02 21 views
8

当前的boost ::用于转换特定的C++异常到蟒蟒例子是这样的:广义例外转换为升压蟒蛇

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

boost::python::register_exception_translator<MyException>(translate); 

不幸的是,这要求我们写一个特定的功能为我们的每一个异常。我们试图简化此,通过编写一个通用的异常译者:

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

请问代码工作, 的那一点,你可以包装实现“是什么()”像这样的例外:

BOOST_PYTHON_MODULE(libtest) 
{ 
    translate<std::out_of_range>(PyExc_RuntimeError); 
} 

不幸的是,它似乎提振:: Python会调用 “翻译” 代码 “升压/蟒蛇/细节/ translate_exception.hpp”(61行)内的功能:

translate(e); 

在我们的广义的异常处理程序,这将是GeneralizedTranslator调用::运算符(),而且不会为G ++工作,并提供:

error: ‘translate’ cannot be used as a function 

有没有写这个正确的方式?

回答

5

您正在传递this指针作为翻译函数,并且由于指向对象的指针无法作为函数调用,因此失败。如果您通过*this而不是这应该工作(请注意,这将复制构建GeneralizedTranslator对象)。或者您可以将注册移出构造函数,并致电

register_exception_translator<std::out_of_range>(GeneralizedTranslator<std::out_of_range>(PyExc_RuntimeError)); 
+0

是的。你说对了!我已经更新了上面的代码,因此它显示了正确的解决方案。谢谢 –