[C++-sig] Incrementing reference count of returned object pointer

Patrick Hartling patrick at vrac.iastate.edu
Fri Nov 22 03:56:13 CET 2002

Patrick Hartling wrote:
> I am having some difficulty using boost::python::call<T>() to invoke a 
> Python function that returns a pointer.  I understand that the callback 
> semantics cause an exception to be thrown if the reference count of the 
> returned object is 1, so I am wondering how to increment the reference 
> count.  The code that receives the reference will be holding onto it, so 
> of course I don't want it to be garbage collected.
> For some background, what I am working on involves an abstract base 
> class written in C++ that will be extended using a derived Python 
> class.  I would like to be able to use Python-defined objects in C++ as 
> though they were polymorphic instances of the base class (which they 
> are--at least conceptually).  My long-term goal is to be able to load 
> Python modules on the fly that define a subclass of the abstract base 
> class.  To get a reference to an instance of the derived Python class, I 
> want to have a factory function that simply returns the instance.  This 
> factory function would be called by the C++ code (via 
> boost::python::call<T>() or some other similarly friendly mechanism), 
> and the result would be treated as a reference to the abstract base 
> class.  What this all boils down to is an interface defined in C++ that 
> can be implemented in Python (or any language) where instances of the 
> interface implementations will be used in C++.  So, given a PyObject* 
> factory_func that is the callable factory function, I want to do 
> something like this:
>    Base* obj = boost::python::call<Base*>(factory_func);

Okay, I think I got this worked out.  Instead of the above, I am doing
the following (assuming namespace python = boost::python):

    python::object base_obj = python::call<python::object>(factory_func);
    Base* obj = python::extract<Base*>(base_obj);

This seems to do the trick.  Is there anything fundamentally wrong with 


Patrick L. Hartling                     | Research Assistant, VRAC
patrick at vrac.iastate.edu                | 2624 Howe Hall: 1.515.294.4916
http://www.137.org/patrick/             | http://www.vrac.iastate.edu/

More information about the Cplusplus-sig mailing list