Getting C++ object from PyObject *

Mike Rovner mike at nospam.com
Thu Sep 25 22:59:51 CEST 2003


Nikolai Kirsebom wrote:
> I'm using BOOST to integrate Python into our application.  Could

Usually *.python.c++ is a better place to discuss boost.python issues.

> someone tell me how I get hold of the C++ object (pointer to the
> object instance) from a PyObject *.
>
> Example:
> I have defined and exposed two C++ classes:
>
> class MyObjectA
> {
> public:
>   MyObject();
> };
>
> class MyObjectB
> {
> public:
>   MyObjectB();
>   void SetInput(PyObject *o);
> };
>
> In Python I'm able to write:
>
> pa = MyObjectA()
> pb = MyObjectB()
>
> to create an instance of each of the classes.
>
> Then using the exposed SetInput method of class MyObjectB:
>
> pb.SetInput(pa)

Unless you have a variety of different inputs to SetInput() you probably
want
void MyObjectB::SetInput(MyObjectA const&)

In that case boost.python will be able to do extract<MyObjectA
const>(object(pa)) by itself
along with some error checking you discuss later:

> How would I code the SetInput method:
>
> void MyObjectB::SetInput(PyObject *o)
> {
> //Check that type of 'o' is an (instance) object of class 'MyObjectA'
> //Fetch the pointer (reference) to the actual instance of MyObjectA
> MyObjectA * ca = .....
> }

Also you might want some lifetime control with_custodian_and_ward<1,2>() to
prevent pa from garbage collection while it's used in pb.

HTH,
Mike








More information about the Python-list mailing list