boost::python and shared_ptr

John Hunter jdhunter at nitace.bsd.uchicago.edu
Mon Aug 20 18:53:59 EDT 2001


I am using boost::python to generate python extensions of some C++
code.

I have a number of abstract base classes that I use polymorphically by
passing pointers to derived classes as pointers to base.  Suppose
Base, Derived and SomeClass are all classes and Derived inherits
publicly from Base and all are exposed to boost::python with
inheritance relationships preserved.

SomeClass's C++ constructor looks like this:
  typedef boost::shared_ptr<Base> PtrBase;
  SomeClass( PtrBase ) 

So here is my problem: if I create an instance if Derived in python,
how do I pass it to SomeClass

d = Derived()
s = SomeClass( d )  //nope: d is not a shared_ptr<Base> 

I would expect this problem would arise frequently: Any suggestions
as to how to solve it?

One approach I have tried is for Base to declare a clone method:

Base:
  virtual PtrBase clone() const=0
 
Derived:
  PtrBase clone() const { return PtrBase( new Derived( *this ) ); }

expose these to python and use it like:

d = Derived().clone()
s = SomeClass( d )  //ok, d is a shared_ptr<Base>

This works sometimes.  Since boost:;python treats shared_ptrs like
references (ie you can call member functions of the pointed to class
with the '.' operator in python), it seems like a neat solution.  You
can access member functions in python and pass it off polymorphically
to classes looking for a Ptrbase.

But the problem is that my code seems to freeze a lot when I run test
cases.  This makes me wonder if there is a reference counting problem
somewhere and objects are being deleted prematurely.  I am using only
shared_ptr -- no raw pointers anywhere.

If anyone has any comments on the design above, or other suggestions
about how to achieve my goal (create objects in python and pass them
off to constructors and member functions looking for pointers to their
base), that would be great.

Thanks,
John Hunter

boost 1.23.0
python 1.6.1



More information about the Python-list mailing list