how to pass C++ object to another C++ function via Python function

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 21 10:17:03 EDT 2008


En Mon, 21 Apr 2008 10:24:15 -0300, grbgooglefan <ganeshborse at gmail.com> escribió:

> I am trying to pass a C++ object to Python function. This Python
> function then calls another C++ function which then uses this C++
> object to call methods of that object's class.
>
> I tried something like this, but it did not work, gave core dump.

You can't pass any arbitrary C object to a Python function.
In this case you can use a PyCObject, a Python box around a void* pointer.
See http://docs.python.org/api/cObjects.html

> // compile this Python function using PyRun_String & get its pointer
> by PyObject_GetAttrString.
> // Later call it as below:
>    myclass myobj(23);
>    PyObject *pTuple = 0;
>    pTuple = PyTuple_New(2);
>    PyTuple_SetItem(pTuple,0,PyString_FromString("NAME")); // for t167
> parameter
>    PyObject *inputarg = Py_BuildValue("OO&",pTuple,myobj); // for
> classobj parameter
>
>    result = PyObject_CallObject(pPyEvalFunction,inputarg);
> }
>
> How can I pass this class object to Python function?
> Is it possible to set it in tuple using PyTuple_SetItem, because I may
> have varying number of arguments for my Python functions & that's why
> I can't use Py_BuildValue.

You have to check every call for errors, and pay attention to the reference counts!
The argument passing is wrong. You never set the second tuple element. An easier way is using PyObject_CallFunctionObjArgs(function, arg1, arg2, NULL)

-- 
Gabriel Genellina




More information about the Python-list mailing list