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

From Sidvind
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

  1. CustomString* factory(const char* str){
  2.     return new CustomString(str);
  3. }
  4.  
  5. struct CustomString_to_PyStr: to_python_converter<CustomString*, CustomString_to_PyStr> {
  6.     static PyObject* convert(CustomString* x) {
  7.         return PyString_FromString(x->c_str());
  8.     }
  9. };
  10.  
  11. void* extract_CustomString(PyObject* op){
  12.     return CustomString::stringWithCString(PyString_AsString(op));
  13. }
  14.  
  15. BOOST_PYTHON_MODULE(Foo){
  16.     CustomString_to_PyStr();
  17.     boost::python::converter::registry::insert(&extract_CustomString, boost::python::type_id<CustomString>());
  18. }

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.