[C++-sig] ownership of C++ object extended in Python
Mark Williams
mark at image-engine.com
Mon Mar 19 21:21:27 CET 2007
In the Python FAQ Wiki at http://wiki.python.org/moin/boost.python/HowTo
I see a heading titled "ownership of C++ object extended in Python"
which discusses how to keep a PyObject* alive while the object it
represents still exists in C++. It suggests writing a wrapper as follows:
class MyClassWrap : public MyClass
{
MyClassWrap( PyObject* self_) : self(self_) { PyINCREF(self); }
MyClassWrap( PyObject* self_, const MyClass& copy ) : MyClass(copy),
self(self_) { PyINCREF(self); }
~MyClassWrap() { PyDECREF(self); }
...
PyObject *self;
};
I'm guessing (probably incorrectly) that this was written before the
introduction of boost::python::wrapper<>. What I'd like to do is
something like..
class MyClassWrap : public MyClass, wrapper<MyClass>
{
MyClassWrap()
{
Py_INCREF( detail::wrapper_base_::get_owner(*this) )
}
~MyClassWrap()
{
Py_DECREF( detail::wrapper_base_::get_owner(*this) )
}
/* ... wrapped methods here ... */
}
class_<
MyClass,
boost::intrusive_ptr<MyClass>,
boost::noncopyable>("MyClass");
.. but of course get_owner returns 0 from within MyClassWrap()
What is the correct way of incrementing/decrementing the reference count
for the underlying PyObject* when using wrapper<>, please?
Thanks in advance,
Mark
More information about the Cplusplus-sig
mailing list