将python嵌入C ++无法正常工作

sk11

我将Python嵌入到C ++应用程序中。

当我运行下面的C ++代码片段时,它向我返回了时间戳,它可以正常工作。

Py_Initialize();    

std::string strModule = "time"; // module to be loaded
pName = PyString_FromString(strModule.c_str());
pModule = PyImport_Import(pName); // import the module

pDict = PyModule_GetDict(pModule); // get all the symbols in the module
pFunc = PyDict_GetItemString(pDict, "time"); // get the function we want to call

// Call the function and get the return in the pValue
pValue = PyObject_CallObject(pFunc, NULL);
if (pValue == NULL){
    printf('Something is wrong !');
    return 0;
}
printf("Return of python call : %d\n", PyInt_AsLong(pValue)); // I get the correct timestamp

Py_Finalize();

现在我想得到sys.path但是类似的代码使我出错:

Py_Initialize();    

std::string strModule = "sys"; // module to be loaded
pName = PyString_FromString(strModule.c_str());
pModule = PyImport_Import(pName); // import the module

pDict = PyModule_GetDict(pModule); // get all the symbols in the module
pFunc = PyDict_GetItemString(pDict, "path"); // get the function we want to call

// Call the function and get the return in the pValue
pValue = PyObject_CallObject(pFunc, NULL);
if (pValue == NULL){
    printf('Something is wrong !'); // I end up here, why pValue is NULL?
    return 0;
}
printf("Return of python call : %d\n", PyInt_AsLong(pValue));

Py_Finalize();

我想问题是time.time()函数调用而sys.path变量。如果是这样的话:

  1. 如何获得变量的结果?
  2. 如何将结果(在本例中为list正确转换为C ++中有意义的东西,例如字符串数组?

如果没有,该如何进行?我正在使用Python 2.7.6

谢谢。

斯拉瓦·巴切里科夫(Slava Bacherikov)

您的问题是PyDict_GetItemString(pDict, "path")将返回python列表,并且无法调用。当您执行时,PyObject_CallObject(pFunc, NULL);您将执行它。等于sys.path()

这应该工作:

PyObject *pName, *pModule, *pDict, *list, *pValue, *item;
int n, i;
char *name;
Py_Initialize();    

std::string strModule = "sys"; // module to be loaded
pName = PyString_FromString(strModule.c_str());
pModule = PyImport_Import(pName); // import the module

pDict = PyModule_GetDict(pModule); // get all the symbols in the module
list = PyDict_GetItemString(pDict, "path"); // get python list
n = PyList_Size(list);
if (n < 0)
    return -1; /* Not a list */

for (i = 0; i < n; i++) { // iterate over list
    item = PyList_GetItem(list, i); /* Can't fail */
    if (!PyString_Check(item)) continue; /* Skip non-string */
    name = PyString_AsString(item);
    std::puts(name);
}


Py_Finalize();
return 0;

完整代码在这里

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章