[C++-sig] Re: Python + Boost Python V2 + downcasting

Nicolas Lelong n_lelong at hotmail.com
Mon Nov 11 19:37:26 CET 2002


David Abrahams wrote:

>[...]
>
> Ultimately, I think the best solution is going to be to add a new kind
> of ReturnValuePolicy which uses typeid() on the pointer to get the
> most-derived class, looks up the corresponding Python class in the
> converter::registry, and builds a pointer_holder around it using the
> appropriate Python class type. Hmm, looking carefully, this might not
> require a new ReturnValuePolicy, and could be as simple as making some
> judicious changes to boost/python/object/make_instance.hpp.**
>

OK Dave,
I've decided to go for it, and I think I've made up the kind of changes
needed in 'boost/python/object/make_instance.hpp'.

I replaced the following line from 'PyObject* make_instance::execute(Arg&
x)' :
    PyTypeObject* type = converter::registered<T>::converters.class_object;
with:
    PyTypeObject* type = query_most_derived_PyTypeObject( x );

Having some news methods in make_instance:

template <class Arg>
static dynamic_id_t query_most_derived_dynamic_id_t(Arg& x)
{
    typedef typename dynamic_id_generator<T>::type generator;
    return generator::execute( (void*)&(*x) );
}

static dynamic_id_t query_most_derived_dynamic_id_t(reference_wrapper<T
const> x)
{
    typedef typename dynamic_id_generator<T>::type generator;
    return generator::execute( (void*)x.get_pointer() );
}

template <class Arg>
static PyTypeObject* query_most_derived_PyTypeObject(Arg& x)
{
    if (is_polymorphic<T>::value)
    {
        dynamic_id_t dynamic_id = query_most_derived_dynamic_id_t( x );
        converter::registration const* registration_data =
converter::registry::query( dynamic_id.second );
        return registration_data->class_object;
    }
    else
    {
        return converter::registered<T>::converters.class_object;
    }
}

It seems to work fine on a few examples I tried here - I must admit that
I've not run the whole test suite, but what do you think of it ?!

Thanks,
Nicolas.

> [...]




More information about the Cplusplus-sig mailing list