[C++-sig] return object from factory function

Gennadiy Rozental rogeeff at gmail.com
Wed Jul 16 22:12:28 CEST 2008


Hi,

I've got factory function that logically looks like this (in reality it's
pluggable factory - but this does not make difference for this question):

Base*
Factory::create( .... )
{
 ....
case python_object:
   boost::python::object obj = m_python_type();

   return boost::python::extract<PythonBase*>( obj )();
}

Here PythonBase is inherited from Base and is exported to python so that python
classes can inherit from it. m_python_type is pre-cached reference to the python
type corresponding to the class inherited from exported PythonBase.

I've noticed though that it does not work if written like above. python object
is destroyed as soon as we leave create scope. what I am end up doing is adding
this statement:

Py_INCREF( obj.ptr() );

Is this right thing to do? Can I avoid C API somehow? Do I need matching DECREF
somewhere?

Thanks,

Gennadiy




More information about the Cplusplus-sig mailing list