[Numpy-discussion] Multidimension array access in C via Python API

Eric Moore ewm at redtetrahedron.org
Mon Apr 4 15:44:51 EDT 2016


/* obj[ind] */
PyObject* DoIndex(PyObject* obj, int ind)
{
    PyObject *oind, *ret;
    oind = PyLong_FromLong(ind);
    if (!oind) {
        return NULL;
    }
    ret = PyObject_GetItem(obj, oind);
    Py_DECREF(oind);
    return ret;
}

/* obj[inds[0], inds[1], ... inds[n_ind-1]] */
PyObject* DoMultiIndex(PyObject* obj, int *inds, int n_ind)
{
    PyObject *ret, *oind, *temp;
    oind = PyTuple_New(n_ind);
    if (!oind)
        return NULL;

    for (int k = 0; k < n_ind; ++k)
    {
        temp = PyLong_FromLong(inds[k]);
        if (!temp)
            Py_DECREF(oind);
        PyTuple_SET_ITEM(oind, k, temp);
    }
    ret = PyObject_GetItem(obj, oind);
    Py_DECREF(oind);
    return ret;
}

/* obj[b:e:step] */
PyObject* DoSlice(PyObject* obj, int b, int e, int step)
{
    PyObject *oind, *ret, *ob, *oe, *ostep;
    ob = PyLong_FromLong(b);
    if (!ob)
        return NULL;
    oe = PyLong_FromLong(e);
    if (!oe) {
        Py_DECREF(ob);
        return NULL;
    }
    ostep = PyLong_FromLong(step);
    if (!ostep) {
        Py_DECREF(ob);
        Py_DECREF(oe);
        return NULL;
    }
    oind = PySlice_New(ob, oe, ostep);
    Py_DECREF(ob);
    Py_DECREF(oe);
    Py_DECREF(ostep);

    if (!oind)
        return NULL;

    ret = PyObject_GetItem(obj, oind);
    Py_DECREF(oind);
    return ret;
}

-Eric

On Mon, Apr 4, 2016 at 1:35 PM, mpc <matt.p.conte at gmail.com> wrote:

> Hello,
>
> is there a C-API function for numpy that can implement Python's
> multidimensional indexing?
>
> For example, if I had a 2d array:
>
>    PyArrayObject * M;
>
> and an index
>
>    int i;
>
> how do I extract the i-th row M[i,:] or i-th column M[:,i]?
>
> Ideally it would be great if it returned another PyArrayObject* object (not
> a newly allocated one, but whose data will point to the correct memory
> locations of M).
>
> I've searched everywhere in the API documentation, Google, and SO, but no
> luck.
>
> Any help is greatly appreciated.
>
> Thank you.
>
> -Matthew
>
>
>
> --
> View this message in context:
> http://numpy-discussion.10968.n7.nabble.com/Multidimension-array-access-in-C-via-Python-API-tp42710.html
> Sent from the Numpy-discussion mailing list archive at Nabble.com.
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> https://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20160404/218c58ee/attachment.html>


More information about the NumPy-Discussion mailing list