从python返回一个数组到c++

Return an array from python to C++

本文关键字:一个 数组 c++ python 返回      更新时间:2023-10-16

我正在编写一个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_namen");
    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 : %dn", PyInt_AsLong(pValue));
        PyErr_Print();
        Py_DECREF(pValue);
    }
    else 
    {
        PyErr_Print();
    }

在这里,pValue应该接受的值是一个数组,但是当它只接受单个元素时,它能够成功执行。

我不能理解数组是如何从python传递到c++的。

Python 列表是一个对象。你能从python返回一个列表并检查你在c++中用PyList_Check得到它吗?然后看看PyList_Size有多长时间,然后把PyList_GetItem的项目捞出来。

我在Chris的指导下解决了上述问题:

当从Python返回数据时,返回一个列表而不是数组。

    pValue = PyObject_CallObject(pFunc, pArgTuple);
    Py_DECREF(pArgTuple);
    if (pValue != NULL) 
    {   
        printf("Result of call: %dn", PyList_Check(pValue));
        int count = (int) PyList_Size(pValue);
        printf("count : %dn",count);
        float temp[count];
        PyObject *ptemp, *objectsRepresentation ;
        char* a11;
        for (i = 0 ; i < count ; i++ )
        {
            ptemp = PyList_GetItem(pValue,i);
            objectsRepresentation = PyObject_Repr(ptemp);
            a11 = PyString_AsString(objectsRepresentation);
            temp[i] = (float)strtod(a11,NULL);
        }

这里,你的临时float数组将保存你从python发送的列表数组。

相关文章: