Boost::Python: Converting to and from custom class pointers

From Sidvind
Revision as of 03:13, 19 February 2007 by EXt (Talk | contribs)

Jump to: navigation, search

Boost::Python series

Site: boost.org (Documentation)

[edit]

NOTE: Sadly this code isn't working 100% correctly, I have a new versions which I will add here soon

Code: Converting your custom class to a python usable class

<cpp/> 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.