当前用于将特定 C++ 异常转换为 python 的 boost::python 示例如下所示:
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);
}
这段代码行得通吗您可以像这样包装实现“what()”的异常:
BOOST_PYTHON_MODULE(libtest)
{
translate<std::out_of_range>(PyExc_RuntimeError);
}
不幸的是,boost::python 似乎会将“翻译”代码作为“boost/python/detail/translate_exception.hpp”中的函数调用(第 61 行):
translate(e);
在我们的通用异常处理程序中,这将是对 GeneralizedTranslator::operator() 的调用,并且不适用于 g++,给出:
error: ‘translate’ cannot be used as a function
有正确的写法吗?
最佳答案
您将 this
指针作为翻译函数传递,这会失败,因为指向对象的指针不能作为函数调用。如果您改为传递 *this
,这应该有效(请注意,这将复制构造 GeneralizedTranslator 对象)。或者您可以将注册移出构造函数,然后调用
register_exception_translator<std::out_of_range>(GeneralizedTranslator<std::out_of_range>(PyExc_RuntimeError));
关于c++ - boost python 的通用异常转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6908976/