python embedding: passing list from C to python function

不想你离开。 提交于 2020-01-01 17:05:53

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/21031856/python-embedding-passing-list-from-c-to-python-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!