[C++-sig] Getting object for PyObject (reference counting)

AFoglia at princeton.com AFoglia at princeton.com
Fri Feb 27 22:44:46 CET 2009

Murray Cumming wrote:
> On Fri, 2009-02-27 at 08:34 -0800, Alex Mohr wrote:
>> Murray Cumming wrote:
>>> I can't find any definitive documentation that tells me how I should get
>>> a boost::python::object to wrap an existing PyObject*. I guess that
>>> there's a way to do it that uses an existing reference, and a way that
>>> takes an extra reference.
>> You can construct a boost::python::object with a 
>> boost::python::handle<>.  boost::python::handle<> is sort of a "smart" 
>> PyObject *.  It manages the python object reference count automatically. 
> Oh, I assumed that boost::python::object did this already.
> If not, is there any reason not to use
> boost::python::handle<boost::python::object> everywhere instead of a
> boost::python::object?
> One of my main reasons for using boost::python instead of the C API is
> to avoid worrying so much about the reference counting. For instance, I
> don't want to explicitly increment the ref when returning a PyObject, or
> remember whether I should take a ref when given a PyObject from various
> functions.

I believe, but could be wrong, that boost::python::objects must be made 
from handles.  If not that's not a requirement, it's at least a strong 
suggestion.  That way, the underlying handle in the object will handle 
the reference counting for you.

The way I understand it, the handle takes care of the reference 
counting, and the object is a wrapper to make it easier to interact with 
the pointer to PyObject in a more OO-like manner.

Also, I'm not sure you can make a 
boost::python::handle<boost::python::object>.  The instance the handle 
points to should be laid out like a PyObject.  (Remember, the underlying 
Python code is C-based, so pointer layout is required to start the same 
to approximate inheritance.)  I don't think boost::python::object can 
make that guarantee.

Anthony Foglia
Princeton Consultants
(609) 987-8787 x233

More information about the Cplusplus-sig mailing list