[C++-sig] Converting existing C++ data to python using Boost.Python

Dave Abrahams dave at boostpro.com
Thu Nov 10 14:31:19 CET 2011


on Thu Nov 10 2011, Wojciech Mamrak <wmamrak-AT-gmail.com> wrote:

> Hello,
>
> I am aware about the possibility to register converters to- and from-
> Python, which enable the implicit conversions between user-defined and
> build-in types in Python.
> My question is different: Is it possible to use Boost.Python to
> convert existing data structures from C++ to Python?
>
> Simple example:
>
> //C++ struct:
> struct Foo {
>     int x, int y;
> };
>
> class_<Foo>("Foo")
>     .def_readwrite("x", &Foo::x)
>     .def_readwrite("y", &Foo::y);
>
> //instance of Foo
> Foo foo = {1, 2};
>
> Now I would like to pass foo object to some Python method. 

If you get the python method into a boost::python::object, you can just
do:

   boost::python::object the_target
   the_target.attr("the_method")(foo);

> Obviously I need to create a Python version of this object.  

Boost.Python can handle that for you behind the scenes.

> Python is aware of the Foo definition thanks to Boost.Python, but
> still, is there any other method of transferring the data than the
> one, which uses some glue function which creates a Python Foo instance
> based on all members of C++ foo passed separately to it? As far as I
> am aware, Python converters are not intended to help here.
>
> The docs claim, that BOOST::PYTHON::Object can not be used as a
> replacement of PyObject, i.e. e.g. it can't be passed to some Python
> function and used inside of it. 

Where?!


-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com



More information about the Cplusplus-sig mailing list