[PyKDE] C++ wrapper at granularity of Python/C API?

Nigel Stewart ns at fluent.com
Sun Apr 9 01:58:52 BST 2006

Hi all,

In the context of our C++/Python/Sip/Qt codebase, we've
had some need for Python-aware C++ classes that utilise
the Python/C API, along with the incref and decref pain
that comes along with that.

I've been toying with the use of boost::intrusive_ptr
and/or boost::python::api::object as C++ wrappers for
PyObject * and some of the potential advantages:

- Default constructor to 0          (no uninitialised PyObject *)
- Destructor to decref and set to 0 (no stale PyObject *)
- Safe copying with implicit incref (automatic incref/decref)

However, when it comes to mixing these "smart pointer"
style wrappers with the Python/C API, there remains
the problem of handling the different scenarios:

- New reference (ref count 1)
- Borrowed reference (ref count >0, incref for long-term use)

So, what would be very nice, would be a whole set of
wrappers for the Python/C API that deal with the reference
counting in a boost::intrusive_ptr or boost::python::api::object
friendly way to make it "idiot-proof".

boost::python encourages use of the Python/C API to the
extent of providing access to the PyObject via
boost::python::api::object::ptr(), but doesn't seem to
provide the entire Python/C API

So, one may need to write

Rather than simply:

The real value would be in the case of say:

     o = python::List_New(10);   // PyList_New produces new reference
     a = o.List_GetItem(4);      // PyList_GetItem returns borrowed reference

     // We're all done without a Py_INCREF or PyDECREF, whew!

Am I missing something obvious in boost::python?

Kind regards,

Nigel Stewart

More information about the PyQt mailing list