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

Murray Cumming murrayc at murrayc.com
Fri Feb 27 22:25:22 CET 2009

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

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

>   When you create a boost::python::handle<> you can tell it whether to 
> bump the reference count or not.  Given a PyObject *p:
> // Use with a "new reference" -- *doesn't* bump ref count.
> handle<>(p);
> // Use with a "borrowed reference" -- *does* bump ref count.
> handle<>(borrowed(p));
> Alex
> _______________________________________________
> Cplusplus-sig mailing list
> Cplusplus-sig at python.org
> http://mail.python.org/mailman/listinfo/cplusplus-sig
Murray Cumming
murrayc at murrayc.com

More information about the Cplusplus-sig mailing list