[C++-sig] Problems with Python "Factories"

Lloyd Weehuizen lloyd at fusion.net.nz
Thu Apr 6 11:04:01 CEST 2006


Hi

I've run into a problem wrapping a C++ base class thats extended in 
Python and contains a factory method.

Here's a simplified example:

class FactoryBaseType
{
};

class FactoryBase
{
    virtual FactoryBaseType*  InstanceType();
};

In python I override this with a concrete type:

import mylib

class ConcreatePythonType( mylib.FactoryBaseType ):
     pass

class Factory( mylib.FactoryBase )
  def InstanceType():
       return ConcreatePythonType()

I've managed to set up the wrappers for the types and everything works 
great up until I call the InstanceType method on a python based factory 
from C++. The object is created and returned correctly to C++ from 
python. The C++ wrapper then uses extract<> to pull out the 
FactoryBaseType and return it to the callee and thats where it all goes 
wrong. When the wrappers InstanceType completes the local 
boost::python::object that has its pointer extracted from goes out of 
scope and the extract'd pointer becomes a dangling pointer as nobody is 
referencing the constructed python object anymore.

I'm not exactly sure how to solve this, do I have to hack around this by 
implementing some kind of temporary reference on the object? Or is there 
some way around this problem that I've missed?

Thanks for your help
Lloyd



More information about the Cplusplus-sig mailing list