[C++-sig] Wrapping already refcounted C++ types
David Abrahams
david.abrahams at rcn.com
Tue Feb 19 16:37:26 CET 2002
----- Original Message -----
From: "Stefan Franke" <franke at ableton.com>
> Dear group,
>
> I would like to wrap a couple of C++ classes in a library that
> already implements its own reference counting.
>
> The instances are never copied by value but referenced either
>
> (a) by plain C pointers or
> (b) by their respective smart pointer class
>
> So I have to write to_python() and from_python() conversions
> for these pointer types.
>
> The behaviour I'd like to implement for case (a) is that the
> wrapper object increments the original instance's refcount when
> created and releases the reference on destruction.
>
> My questions are:
>
> - Where are the right places to put the respective incref/decrefs?
> - What to do in case (b)
(b) is easy. (a) is hard without Boost.Python v2.
For (b):
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
PyObject* to_python(smart_ptr<Foo> p)
{
return
boost::python::python_extension_class_converters<Foo>::smart_ptr_to_python(p
);
}
template <class T>smart_ptr<T> from_python(PyObject*p,
boost::python::type<smart_ptr<T> >)
{
return smart_ptr_from_python(p, boost::python::type<smart_ptr<T> >(),
boost::python::type<T>());
}
template <class T>smart_ptr<T> from_python(PyObject*p,
boost::python::type<smart_ptr<T> const&>)
{
return from_python(p, boost::python::type<smart_ptr<T> >());
}
BOOST_PYTHON_END_CONVERSION_NAMESPACE
For (a), You'll need to creat a thin wrapper function over all of your
functions manipulating the raw pointers. The easiest way is to replace the
raw pointers in the signature with PyObject*, manipulate the reference
counts in your wrapper function, then exploit from_python(p,
boost::python::type<Foo*>()) directly to get the argument for the wrapped
function.
-Dave
More information about the Cplusplus-sig
mailing list