[C++-sig] Python __init__ that copies internal reference, boost.python

Jim Bosch talljimbo at gmail.com
Mon Aug 16 23:49:04 CEST 2010


On 08/16/2010 02:33 PM, Branan Purvine-Riley wrote:
> I'm working on replacing hand-rolled python bindings with boost.python.
> Unfortunately, I've hit a bit of a snag at a particular construct:
>
>    a = someFunction(...) # returns an instance of myClass
>    b = myClass(a)
>
> In the current bindings, this creates a new python object that references the
> same internal C++ object. It's effectively no-op, and I have no idea why it was
> written that way in the first place, but I have to maintain API compatibility.
>
> That being the case, how do I implement this in boost.python? I considered
> replacing __init__, but it seems if I implement that as a standalone function
> rather than a constructor, boost has already created a new C++ instance for
> me, so that's too late. I'm not really sure what else to try.

You'll want to use the make_constructor function; this takes a C++ 
function returning a C++ smart pointer and creates a Python __init__ 
overload.

I *think* this should work (I haven't tested it):

----------------------------------------------

boost::shared_ptr<MyClass> construct(boost::python::object const & arg) {
     return boost::python::extract< boost::shared_ptr<MyClass> >(arg);
}

BOOST_PYTHON_MODULE(example) {
     boost::python::class_<MyClass>("MyClass")
         .def("__init__", boost::python::make_constructor(&construct))
         ;
     boost::python::register_ptr_to_python<
         boost::shared_ptr<MyClass>
     >();
}

----------------------------------------------

Hope that helps.

Jim Bosch



More information about the Cplusplus-sig mailing list