[C++-sig] Re: call_method

David Abrahams dave at boost-consulting.com
Sat Nov 16 14:06:28 CET 2002

"Brett Calcott" <brett.calcott at paradise.net.nz> writes:

>> I'm thinking we should do this:
>> 1. Set up Boost.Python so that shared_ptr<T> can be extracted from any
>> Python object from which we can extract T*... no matter how it's
>> held! You can do this by using a custom deleter that holds the Python
>> object and keeps it alive. See the section titled:
>>    "Using a shared_ptr to Hold Another Shared Ownership Smart Pointer"
>> I find this very exciting, and can't believe I didn't think of it
>> earlier!!
>> 2. Prepare a special "self_base" class that can be used as a base of
>>    "callback" classes like BaseWrap from the examples. This base would
>>    hold the "self" pointer. It would also provide a family of
>>    convenience functions which implement call_method<> on the held
>>    self pointer without having to explicitly mention it (hmm, I'm not
>>    sure I can make this work out on msvc6. But that's another
>>    issue). Most-importantly, when references and (smart) pointers to
>>    polymorphic classes are converted to python, we will attempt to
>>    downcast to "self_base", and if successful, we'll return the
>>    contained self pointer instead of a new object.
> Ok, I understand 2. This gets around having to create to_python
> converters.

> But I don't yet see how 1. can work. Is the 'other shared pointer' the
> Python reference count? 


> Or the shared_ptr declared in class_<...>? 

No, that's my point: we can do it /no matter how the T is held/.

First imagine using handle<> as the 'other shared ptr' . Then you
can easily replace it with PyObject* :

struct pyobject_deleter
    pyobject_deleter(handle<> p): p_(p)

    void operator()(void const *)
    handle<> p_;

template <class T>
shared_ptr<T> make_shared(PyObject* p)
    extract<T*> x(p);
    if (x)
        return shared_ptr<T> px(x(), pyobject_deleter(handle<>(borrowed(p)))));
        // conversion failed

                       David Abrahams
   dave at boost-consulting.com * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution

More information about the Cplusplus-sig mailing list