簡體   English   中英

將一個 numpy 數組從 Python 傳遞給 C

[英]Pass a numpy array from Python to C

我已成功將 Python 腳本嵌入到 C 模塊中。 Python 腳本生成一個多維 Numpy 數組。 Python 中的整個計算需要 9 毫秒,而將其返回到 C 的最終 tolist() 轉換僅需要 4 毫秒。 我想通過將 Numpy 數組作為參考傳遞並再次在 C 中進行迭代來改變它。 但我目前無法弄清楚,如何做到這一點。

周圍有很多示例,它們使用另一種方式:將 Numpy 數組傳遞給從 Python 調用的 C 函數,但這不是我的用例。

歡迎任何指針。

好的,這是前一段時間,但我是這樣解決的:

我的python進程傳遞了一個數組,包含一個數組,包含一個數組,每個包含M個浮點數的N個數組。 輸入是 JPEG 圖像。

像這樣解開它:

int predict(PyObject *pyFunction, unsigned char *image_pointer, unsigned long image_len) {

    int result = -1;

    PyObject *pImage = NULL;
    PyObject *pList = NULL;

    pImage = PyBytes_FromStringAndSize((const char *)image_pointer, image_len);
    if (!pImage) {
        fprintf(stderr, "Cannot provide image to python 'predict'\n");
        return result;
    }

    pList = PyObject_CallFunctionObjArgs(pyFunction, pImage, NULL);
    Py_DECREF(pImage);

    PyArrayObject *pPrediction = reinterpret_cast<PyArrayObject *>(pList);
    if (!pPrediction) {
        fprintf(stderr, "Cannot predict, for whatever reason\n");
        return result;
    }

    if (PyArray_NDIM(pPrediction) != 4) {
        fprintf(stderr, "Prediction failed, returned array with wrong dimensions\n");
    } else {
        RESULTPTR pResult = reinterpret_cast<RESULTPTR>(PyArray_DATA(pPrediction));

        int len0 = PyArray_SHAPE(pPrediction)[0];
        int len1 = PyArray_SHAPE(pPrediction)[1];
        int len2 = PyArray_SHAPE(pPrediction)[2];
        int len3 = PyArray_SHAPE(pPrediction)[3];

        for (int i = 0; i < len0; i++) {
            int offs1 = i * len1;
            for (int j = 0; j < len1; j++) {
                int offs2 = j * len2;
                for (int k = 0; k < len2; k++) {
                    int offs3 = k * len3;
                    for (int l = 0; l < len3; l++) {
                        float f = (*pResult)[offs1 + offs2 + offs3 + l];
                        //printf("data: %.8f\n", f);
                    }
                }
            }
        }
        result = 0;
    }
    Py_XDECREF(pList);
    return result;
}

HTH

暫無
暫無

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

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