问题描述
我正在编写一个c ++代码来调用python函数,并且从python函数返回的数组将存储在c ++中的数组中.我可以在c ++中调用python函数,但是我只能从Python返回一个值到C ++,而我想返回的是一个数组.下面是我的C ++代码:
I'm writing a c++ code to call a python function and the returned array from the python function will be store in an array in c++. I am able to call the python function in c++ but I am able to return only one value from Python to C++ and what I want to return is an array. Below is my C++ code:
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应该采用的值是一个数组,但仅包含单个元素时就能够成功执行.
Here, the value which pValue should take is an array but am able to successfully execute when it takes a single element only.
我无法理解如何将数组从python传递给C ++.
I am not able to understand how will an array be passed from python to C++.
推荐答案
Python list 是1个对象.您可以从python返回一个列表,并使用 PyList_Check
检查是否在C ++中获得了该列表吗?然后查看使用 PyList_Size
多长时间,然后使用 PyList_GetItem
钓鱼.
A Python list is 1 object. Can you return a list from python and check that you got it in C++ with PyList_Check
? Then see how long it is with PyList_Size
and fish out the items with PyList_GetItem
.
这篇关于从python返回数组到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!