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

Paul Melis pyplusplus at assumetheposition.nl
Tue Dec 9 20:10:37 CET 2008


Ralf W. Grosse-Kunstleve wrote:
>> 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.
>   
Hey, that's really nice! I'll try that...

Thanks,
Paul



More information about the Cplusplus-sig mailing list