簡體   English   中英

C返回具有錯誤值的numpy數組

[英]C returning numpy array with incorrect values

下面的擴展只是一個小測試,它使用PyArray_SimpleNewFromData()函數將C到python的整數數組作為numpy數組輸出。

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <numpy/arrayobject.h>
#include <stdio.h>
#include "test_func.h"


static PyObject *sum_c(PyObject *self, PyObject *args)
{

    PyObject *result;
    int a, b;
    int ans[1]={1};
    npy_intp dims[1] = {1};


    //Parse arguments
    if (!PyArg_ParseTuple(args, "ii", &a, &b)){
        return NULL;
    }

    result = PyArray_SimpleNewFromData(1, &dims[0], NPY_INT, ans);

    return result;
}


static PyMethodDef module_methods[] = {
    {"sum_c", sum_c, METH_VARARGS, "Sum two unsigned integers and returns the answer in numpy dtype"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC init_test_func(void){
    (void) Py_InitModule("_test_func", module_methods);
    import_array();
}

編譯並導入python之后,結果是一個1x1 numpy數組,其值不為1(在代碼中為測試值)。

我最好的猜測是C dtype的解釋,盡管NPY_INT應該與C中的INT dtype相匹配?

發現錯誤后,我需要malloc()返回變量,如下所示:

PyObject *result;
    int a, b;
    //int ans[1]={1};
    int *ans;
    npy_intp dims[1] = {1};

    ans = (int *)malloc(1*sizeof(int));
    ans[0] = 4; 

暫無
暫無

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

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