Return an array from python to C++

独自空忆成欢 提交于 2021-02-08 07:41:06

问题


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();
    }

Here, the value which pValue should take is an array but am able to successfully execute when it takes a single element only.

I am not able to understand how will an array be passed from python to C++.


回答1:


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.




回答2:


I was able to solve the above problem with the help of Chris's guidance as follows:

When returning the data from Python, return a list instead of an array.

    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);
        }

Here, your temp array of float will hold the array which you sent as a list from python.



来源:https://stackoverflow.com/questions/30720121/return-an-array-from-python-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!