[C++-sig] Re: Wrapper for exception translation
gritsch at iue.tuwien.ac.at
gritsch at iue.tuwien.ac.at
Thu Apr 14 09:33:22 CEST 2005
Hi,
I am also looking forward to some mechanism to integrate custom exceptions
nicely with Boost.Python. However, in the meantime I use the following
approach, and I wonder, if this is currently the correct way:
--- 8< ---
#include <string>
#include <boost/python.hpp>
struct MyException {
std::string what() const {
return "MyException occurred";
}
};
void throw_it() {
throw MyException();
}
static PyObject * my_exception = NULL;
void translator( MyException const & e ) {
PyErr_SetString( my_exception, e.what().c_str() );
}
BOOST_PYTHON_MODULE( extest ) {
my_exception = PyErr_NewException( "extest.MyException", NULL, NULL );
PyModule_AddObject( boost::python::scope().ptr(), "MyException",
my_exception );
boost::python::register_exception_translator<MyException>( translator );
boost::python::def( "throw_it", throw_it );
}
--- 8< ---
Do I really have to use the Python C-API funcions PyErr_NewException and
PyModule_AddObject?
The module can be used from Python as
--- 8< ---
import extest
try:
extest.throw_it()
except extest.MyException, msg:
print msg
--- 8< ---
Thank you for reading, and please excuse the accidentally sended incomplete
email,
Markus
----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.
More information about the Cplusplus-sig
mailing list