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

Roman Yakovenko roman.yakovenko at gmail.com
Thu Apr 6 11:31:31 CEST 2006


On 4/6/06, Lloyd Weehuizen <lloyd at fusion.net.nz> wrote:
> 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


you should override __init__ method. You have to call
mylib.FactoryBaseType.__init__

> class Factory( mylib.FactoryBase )

same as above

>   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?

I am almost sure the code that you will add will solve your problem

> Thanks for your help
> Lloyd
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
>


--
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list