簡體   English   中英

從python返回數組到C ++

[英]Return an array from python to C++

我正在編寫一個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 清單是1個物件。 您可以從python返回一個列表,並使用PyList_Check檢查是否在C ++中得到它嗎? 然后看到它是怎么長着PyList_Size撈出用物品PyList_GetItem

在Chris的指導下,我能夠解決上述問題:

從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作為列表發送的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM