Getting C++ object from PyObject *

N

Nikolai Kirsebom

I'm using BOOST to integrate Python into our application. Could
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)

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 = .....
}

Thanks for any help.

Nikolai
 
E

Erwin S. Andreasen

Nikolai Kirsebom said:
I'm using BOOST to integrate Python into our application. Could
someone tell me how I get hold of the C++ object (pointer to the
object instance) from a PyObject *.
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 = .....

If you want setInput to be able to take any python object, use the
"object" type instead that boost::python provides. That will take care
of refcounting etc. and provide easier access to calling methdos on
the Python objects.

Once you have an object, you can try a conversion using "extract":

MyObjectA *m = extract<MyObjectA*>(o);

This throws on failure. There's another way to do it, which doesn't
throw. See:

http://www.boost.org/libs/python/doc/tutorial/doc/extracting_c___objects.html


However, I'm not sure you need this manual work at all -- just making
SetInput take a MyObjectA* directly should make boost::python generate
the correct code in the wrapper, and raise an exception if the types
do not match.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top