2

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?

Akhil
  • 2,269
  • 6
  • 32
  • 39
  • 1
    Do you have the error checking code in your actual code? – jfs Jan 10 '14 at 01:05
  • I added PyErr_PrintEx() after PyObject_CallObject, and it says that TypeError: argument list must be a tuple. Cant the argument be a list? – Akhil Jan 10 '14 at 18:56
  • 1
    an argument can be a list. `arglist` must be a tuple that has a list as the only item in your case. Check for errors every call in C. In particular, check `Py_BuildValue()` returned value. – jfs Jan 10 '14 at 19:24
  • Indeed Py_BuildValue() is giving this error - SystemError: bad format char passed to Py_BuildValue. Any idea what is wrong? – Akhil Jan 12 '14 at 20:37

1 Answers1

2

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)

Akhil
  • 2,269
  • 6
  • 32
  • 39
  • 1
    actually, `Py_BuildValue('(O)', l)` is wrong. `Py_BuildValue("(O)", l);` is correct, as c++ needs double quotes for strings. – Collin Bell Oct 23 '17 at 01:08