[C++-sig] Custom from-python converter (almost working)

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Mon Dec 8 18:11:09 CET 2008


> In SWIG it is possible to simply define an extra class method that takes a
> PyObject* and perform any conversion you want in that method (although
> this means having to add that extra method for all cases where the
> non-const pointer is used). Would something similar work in Boost.Python,
> e.g.
> 
> class C
> {
> public:
>     void set_data(data* d);
> };
> 
> void
> extra_method(C& self, PyObject *obj)
> {
>     // if obj is list of tuples, convert to
>     // data* and
>     // call self.set_data(d)
> }
> 
> class_<C>("C")
>   .def("set_data", &C::set_data)
>   .def("set_data", &C::extra_method)
> ;

Yes, this should work if you use boost::python::object:

  void
  extra_method(C& self, boost::python::object obj)

The conversion code in the body of this function will probably be
similar to what you see in the container_conversion.h file.

You could also use

  void
  extra_method(C& self, boost::python::list list_of_tuples)

which will save you one manual conversion step.

Ralf



More information about the Cplusplus-sig mailing list