【问题标题】:Return an array from python to C++从python返回一个数组到C++
【发布时间】: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


    【解决方案1】:

    一个 Python list 是 1 个对象。你能从 python 中返回一个列表并检查你是否使用PyList_Check 在 C++ 中得到它?然后看看PyList_Size的时间有多长,用PyList_GetItem捞出物品。

    【讨论】:

    • @Christopher..非常感谢您的指导..前两个步骤是正确的,但第三步并不适用,因为我发送的数据是浮点数组的形式,但是当它接收到它是 char 数组的形式。但是通过更多的操作,我能够完成我渴望做的事情。再次感谢:)
    【解决方案2】:

    在克里斯的指导下,我能够解决上述问题,如下所示:

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

        pValue = PyObject_CallObject(pFunc, pArgTuple);
        Py_DECREF(pArgTuple);
        if (pValue != NULL) 
        {   
    
            printf("Result of call: %d\n", PyList_Check(pValue));
            int count = (int) PyList_Size(pValue);
            printf("count : %d\n",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 发送的数组。

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2023-04-08
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      相关资源
      最近更新 更多