【发布时间】:2015-06-08 22:26:05
【问题描述】:
我正在编写一个 C++ 代码来调用一个 Python 函数,从 Python 函数返回的数组将存储在 C++ 的一个数组中。我可以在 c++ 中调用 python 函数,但我只能将一个值从 Python 返回到 C++,而我想要返回的是一个数组。下面是我的 C++ 代码:
int main(int argc, char *argv[])
{
int i;
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
if (argc < 3)
{
printf("Usage: exe_name python_source function_name\n");
return 1;
}
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString(argv[1]);
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, argv[2]);
pValue = PyObject_CallObject(pFunc, NULL);
if (pValue != NULL)
{
printf("Return of call : %d\n", PyInt_AsLong(pValue));
PyErr_Print();
Py_DECREF(pValue);
}
else
{
PyErr_Print();
}
这里,pValue 应该取的值是一个数组,但是当它只取单个元素时能够成功执行。
我无法理解如何将数组从 python 传递到 C++。
【问题讨论】:
标签: python c++ arrays python-c-api