Boost logo

Boost :

From: Rainer Deyke (root_at_[hidden])
Date: 2001-04-02 01:04:35


----- Original Message -----
From: "David Abrahams" <abrahams_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Sunday, April 01, 2001 9:55 PM
Subject: Re: [boost] creating a BPL instance from an existing C++ object.

>
> ----- Original Message -----
> From: "Rainer Deyke" <root_at_[hidden]>
>
> > If the object is created by Python, its real class is usually
> > 'boost::python::held_instance<C>'.
>
> ...but might well be boost::python::held_instance<B>, where C is derived
> from B.

I think you mean "where B is derived from C". Some sort of
downcast-to-most-derived-class system would take care of this and other
problems, although at possibly significant performance cost.

> > We can then defined 'boost::python::to_python<C *>' like
> > this:
> >
> > template <class C> PyObject *to_python(C *c)
> > {
> > held_instance<C> *held = dynamic_cast<held_instance<C> *>(c);
> > if (held) {
> > Py_INCREF(held->boost_py_object);
> > return held->boost_py_object;
> > } else {
> > return 0; // Either that or raise an exception.
> > }
> > }
>
> This will only work when C has at least one virtual function :-(

True. I hadn't considered that.

> > This can probably be generalized to include cases where
> > 'boost::python::held_instance' is not used.
>
> What do you have in mind?

template <class T, class U = boost::python::detail::held_instance<T> >
class python_extension_class_converters {
  friend PyObject *to_python(C *c)
  {
    U *held = dynamic_cast<U *>(c);
    if (held) {
      PyObject *o = get_instance_from_held(held);
      Py_INCREF(o);
      return o;
    }
  }
};

We either require that the writer of 'U' provides the appropriate
'get_instance_from_held' overload, or we provide some kind of automation
(i.e. an optional template argument for 'boost::python::class_builder' that
indicates that the existance of a public 'boost_python_instance' member
variable).

--
Rainer Deyke (root_at_[hidden])
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk