我将 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
它是一个变量。如果是这样的话:
- 如何获得变量的结果?
- 如何正确地将结果(在本例中为 a
list
)转换为 C++ 中有意义的内容,例如字符串数组?
如果没有,如何进行?我正在使用 Python 2.7.6
谢谢。