Search code examples
pythonc++clistpython-embedding

python embedding: passing list from C to python function


Trying to pass a list to python from C++ is not working. Here is the relevant code ( written using other related postings):

Py_Initialize();
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyString_FromString("."));

// Build the name object
pName = PyString_FromString("MySolver");

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference 
pFunc = PyObject_GetAttrString(pModule, "mysolve");

if (!PyCallable_Check(pFunc))
  PyErr_Print();

PyObject *l = PyList_New(xvarcount);
for(size_t i=0; i<xvarcount; i++){
  pValue = PyInt_FromLong(0);
  PyList_SetItem(l, i, pValue);
}

PyObject *arglist = Py_BuildValue("(o)", l);
pValue = PyObject_CallObject(pFunc, arglist);

The python script MySolver.py is:

def mysolve(vals):
    print vals
    return 0

I am doing everything as suggested elsewhere. mysolve function just does not get called and the C++ program just proceeds forward without reporting any error at the PyObject_CallObject function call. Note that the code works fine, if I pass a single argument as a tuple to the my solve function. But with a list it is not working. Any ideas, why it is not working?


Solution

  • Usage of Py_BuildValue was erroneous. The documentation of this method on the web e.g. http://docs.python.org/release/1.5.2p2/ext/buildValue.html has this typo, which is why I used small o instead of capitalized O. The correct call is: Py_BuildValue('(O)', l)