[C++-sig] Incrementing reference count of returned object pointer
Patrick Hartling
patrick at vrac.iastate.edu
Wed Nov 20 21:56:57 CET 2002
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);
As I understand it, the need to deal with the reference counting means
that my code can't be quite that simple. I have the Python module
implemented to the point where I can write a Python application that
instantiates the derived class and hands it off to the C++ code. The
next step is having the C++ code request the derived class instance from
a given module.
I've done a little bit of searching around, and I saw a reference to
boost::python::handle<T> as a mechanism to deal with reference-counted
Python objects. Is that the way to go, and if so, how do I use this
class? The Boost.Python reference doesn't have an example, so I am not
sure how to put it to use.
-Patrick
--
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