[C++-sig] Is there a way to automatically convert a smart_ptr to a held_type (try 2)

Allen Bierbaum abierbaum at gmail.com
Thu Aug 31 22:06:26 CEST 2006


Is there a way while access a wrapped object in python to ask it the
type of the currently in use held_type?  In other words, is there a
way I can write a test case in python that will make sure things are
behaving as I want them and that I am not using a ptr<Base> to hold
the C++ object behind the scenes?

-Allen

On 8/30/06, David Abrahams <dave at boost-consulting.com> wrote:
> Alex Mohr <amohr at pixar.com> writes:
>
> >> What I need is a way to tell boost python that anytime it needs to
> >> convert a ptr<Base> to python it should first convert it to a
> >> ref_ptr<Base>  (using a standard copy constructor in ref_ptr<>) and
> >> then use this ref_ptr as the held type like normal.
> >>
> >> At first I thought that implicitly_convertible<> would help:
> >>
> >> implicitly_convertible<ptr<Base>, ref_ptr<Base> >();
> >>
> >> But this doesn't seem to do anything for me. (this really isn't too
> >> surprising since this isn't what implicitly_convertible is for, but it
> >> seemed worth a try).
> >>
> >> Has anyone else ran into anything similar?  Any ideas?
> >
> > At first glance, it seems like you want to register a to-python
> > conversion for all your ptr<T> types.
>
> Good idea.
>
> > Note that all code I write in
> > this message is untested:
> >
> > template <class T>
> > struct ptr_to_python {
> >      static PyObject *convert(ptr<T> const &p) {
> >          return Py_INCREF(object(ref_ptr<T>(p)).ptr());
> >      }
> > };
> >
> > Then you need to do this for each class you register:
> >
> > to_python_converter<ptr<T>, ptr_to_python<T> >();
>
> Looks good so far.
>
> > You could automate this in a custom def visitor:
> >
> > struct ref_ptr_stuff : def_visitor<ref_ptr_stuff> {
> >      friend class def_visitor_access;
> >      template <typename Class>
> >      void visit(Class &c) const {
> >          typedef typename Class::wrapped_type T;
> >          to_python_converter<ptr<T>, ptr_to_python<T> >();
> >      }
> > };
>
> That is a very clever and elegant abuse of def_visitor, I must say!
>
> --
> Dave Abrahams
> Boost Consulting
> www.boost-consulting.com
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
>



More information about the Cplusplus-sig mailing list