Updating numpy array pre 1.14 before PyArray_ResolveWritebackIfCopy()

Viewed 49

Update

Not too long after posting this, I got it working. I debated just deleting the question but it may be of some use to someone.

I started looking at the various version of numpy. I see that they revise the API at a different rate than they version the code (which I agree is a good idea, yet was confusing me). I found out what to do by reviewing the documentation of numpy 1.15. In that version someone wrote the example code so that it ran on both API versions. Thanks! If you would like to compare it with what I did wrong below see Section 7.1.5 of the numpy 1.15 users' manual

Original

I want to accept a numpy array from python, modify it, and return it. I don't mind other solutions. The following code works on numpy 1.14+ but I need to use 1.12. Please note that I am unable to upgrade numpy and I know its a really old version. The code which runs on 1.14+, but fails before then:

static PyObject *ndarray_sync(PyObject *self, PyObject *args) {
    PyObject* arg1 = NULL;
    PyObject* arr1 = NULL;
    PyObject* out = NULL;
    PyObject* oarr = NULL;
    if (!PyArg_ParseTuple(args, "OO!", &arg1, &PyArray_Type, &out)) {return NULL;}
    arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);
    if (arr1 == NULL) {return NULL;}
    // TODO: Later examples use NPY_ARRAY_INOUT_ARRAY2 below, but not supported in numpy 1.12
    // TODO: Not sure what to do
    oarr = PyArray_FROM_OTF(out, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY);
    if (oarr == NULL) {goto fail;}

    // Do work
    int nd = PyArray_NDIM(arr1);
    fprintf(stderr, "ndim (nd) = %i\n", nd);
    npy_intp* dims = PyArray_DIMS(arr1);
    fprintf(stderr, "%i x %i\n", (int)dims[0], (int)dims[1]);

    double* dptr = (double *)PyArray_DATA(arr1);
    dptr[0] = 4;
    fprintf(stderr,"o,o:=%f\n", dptr[0]);
    fprintf(stderr,"o,1:=%f\n", dptr[1]);
    addscalar(dptr, (int)(dims[0] * dims[1]), 5);

    Py_DECREF(arr1);
    PyArray_ResolveWritebackIfCopy(oarr);
    Py_DECREF(oarr);
    Py_INCREF(Py_None);
    return Py_None;

fail:
    Py_XDECREF(arr1);
    PyArray_ResolveWritebackIfCopy(oarr);
    Py_XDECREF(oarr);
    return NULL;
}

When I compile my extension, I receive the following warning:

47:5: warning: implicit declaration of function 'PyArray_ResolveWritebackIfCopy' [-Wimplicit-function-declaration]
     PyArray_ResolveWritebackIfCopy(oarr);

And when I actually call my function, it can't find PyArray_ResolveWritebackIfCopy():

...  .so: undefined symbol: PyArray_ResolveWritebackIfCopy

How might I implement the function above in pre 1.14 numpy?

0 Answers
Related