Getting C++ object from PyObject *

Erwin S. Andreasen erwin at andreasen.com
Sun Sep 28 14:46:23 EDT 2003


Nikolai Kirsebom <nikolai.kirsebom.NOJUNK at siemens.no> writes:

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



-- 
===============================================================
<erwin at andreasen.org>                           Herlev, Denmark     
<URL:http://www.andreasen.org/>                             <*>   
===============================================================





More information about the Python-list mailing list