Boost logo

Boost :

From: Rainer Deyke (root_at_[hidden])
Date: 2001-04-01 22:01:30


----- Original Message -----
From: "David Abrahams" <abrahams_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Sunday, April 01, 2001 8:49 AM
Subject: Re: [boost] creating a BPL instance from an existing C++ object.
> > // Object retrieved from Python, then passed back through a different
> > function:
> > class C {
> > public:
> > set_d(D *d) { this->d = d; }
> > D* get_d() const { return this->d; }
> > private:
> > D *d;
> > };
>
> I only see two possible approaches for this case:
>
> 1. use "unmanaged", making the Python code dangerous
> 2. register every managed C++ object in some kind of map so that the
> corresponding PyObject can be found. This seems way too expensive to me.

If the object is created by Python, its real class is usually
'boost::python::held_instance<C>'. 'boost::python::held_instance<C>' could
be modified to remember the 'PyObject *' that it is the first argument to
its constructors. 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 can probably be generalized to include cases where
'boost::python::held_instance' is not used.

--
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