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?

4
  • 1
    Do you have the error checking code in your actual code? Commented Jan 10, 2014 at 1: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? Commented Jan 10, 2014 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. Commented Jan 10, 2014 at 19:24
  • Indeed Py_BuildValue() is giving this error - SystemError: bad format char passed to Py_BuildValue. Any idea what is wrong? Commented Jan 12, 2014 at 20:37

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

actually, Py_BuildValue('(O)', l) is wrong. Py_BuildValue("(O)", l); is correct, as c++ needs double quotes for strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.