Boost::Python: Converting to and from custom class pointers
From Sidvind
|
NOTE: Sadly this code isn't working 100% correctly, I have a new versions which I will add here soon
- CustomString* factory(const char* str){
- return new CustomString(str);
- }
- struct CustomString_to_PyStr: to_python_converter<CustomString*, CustomString_to_PyStr> {
- static PyObject* convert(CustomString* x) {
- return PyString_FromString(x->c_str());
- }
- };
- void* extract_CustomString(PyObject* op){
- return CustomString::stringWithCString(PyString_AsString(op));
- }
- BOOST_PYTHON_MODULE(Foo){
- CustomString_to_PyStr();
- boost::python::converter::registry::insert(&extract_CustomString, boost::python::type_id<CustomString>());
- }
With this code we can convert to and from a custom string class. In python we use the regular strings and in C++ we can use our custom string class. This would work with any class of course.