typecasting PyArrayObject data to a C array

核能气质少年 提交于 2019-12-04 06:08:32

I think you'll want to look at this: http://docs.scipy.org/doc/numpy/reference/c-api.array.html

In particular,

void* PyArray_GETPTR3(PyObject* obj, <npy_intp> i, <npy_intp> j, <npy_intp> k)

and friends. Those are the functions that David Heffernan would be surprised if the API didn't provide.

I'm not sure if this answers your question but, to reach your NumPy data in C, you could try to create an iterator to loop over your array in C. It doesn't give you indexing you're after ([i][j]) but it covers the entire array

static PyObject *func1(PyObject *self, PyObject *args) {
    PyArrayObject *X;
    int ndX;
    npy_intp *shapeX;
    NpyIter *iter;
    NpyIter_IterNextFunc *iternext;
    PyArray_Descr *dtype;
    double **dataptr;

    PyArg_ParseTuple(args, "O!", &PyArray_Type, &X);
    ndX = PyArray_NDIM(X);
    shapeX = PyArray_SHAPE(X);
    dtype = PyArray_DescrFromType(NPY_DOUBLE);
    iter = NpyIter_New(X, NPY_ITER_READONLY, NPY_KEEPORDER, NPY_NO_CASTING, dtype);
    iternext = NpyIter_GetIterNext(iter, NULL);
    dataptr = (double **) NpyIter_GetDataPtrArray(iter);
    do {
        cout << **dataptr << endl; //Do something with the data in your array
    } while (iternext(iter));   
    NpyIter_Deallocate(iter);
    return Py_BuildValue(...);
}

This is the dirtiest of all answers here, I guess, but 2 years ago, I ended up implementing this function like this:

Just adding it here for documenting it. If you are reading this, you should check out other solutions, which are better.

https://gist.github.com/mehmetalianil/6643299

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