I am creating some C extension code for python (example below). Part of the function requires me to iterate arrays passed in as arguments, preform a calculation on each element, and return an array of the calculated values.
I am using NpyIter_MultiNew
as it can iterate over multiple arrays and also create an appropriate array for the output.
NpyIter_MultiNew
requires a C array of PyArrayObject *
as input (here op
).
op
is filled from the output of PyArray_FROM_OTF
.
These are new references and so I need to clean up at the end of the code.
The question I have is what do I need to `DECREF on? (i.e. what should go in the <>)
Option 1:
Py_XDECREF(op);
Option 2:
Py_XDECREF(op[0]);
Py_XDECREF(op[1]);
Py_XDECREF(op[2]);
Option 3:
Py_XDECREF(op[0]);
Py_XDECREF(op[1]);
Py_XDECREF(op[2]);
Py_XDECREF(op);
I think Py_XDECREF(op[0])
might also be unnecessary.
I suspect that op[0]
remains as NULL
and is simply used as a flag to NpyIter_MultiNew
to indicate the creation of a new array.
The new output array is recovered from output = NpyIter_GetOperandArray(iter)[0];
Note:
The references used in PyObject * args_in[2]
are borrowed and so no INCREF
or DECREF
is required.
static PyObject *
UseArray(PyObject * args){
PyObject * args_in[2];
PyArrayObject * op[3] = {NULL, NULL, NULL};
npy_uint32 op_flags[3];
PyArrayObject * output = NULL;
// python inputs
if (!PyArg_ParseTuple(args, "OO", &args_in[0], &args_in[1])){
goto fail;
}
// output array
op[0] = NULL;
op_flags[0] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE;
// input array
op[1] = (PyArrayObject *) PyArray_FROM_OTF(args_in[0], NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);
op_flags[1] = NPY_ITER_READONLY;
if (op[1] == NULL){
goto fail;
}
op[2] = (PyArrayObject *) PyArray_FROM_OTF(args_in[1], NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);
op_flags[2] = NPY_ITER_READONLY;
if (op[2] == NULL){
goto fail;
}
// iterate
iter = NpyIter_MultiNew(3, op, NPY_ITER_EXTERNAL_LOOP, NPY_KEEPORDER, NPY_NO_CASTING, op_flags, NULL);
<<iterator code>>
// get output array
output = NpyIter_GetOperandArray(iter)[0];
Py_INCREF(output);
if (NpyIter_Deallocate(iter) != NPY_SUCCEED){
goto fail;
}
<<DECREF op>>
return PyArray_Return(output);
fail:
<<DECREF op>>
Py_XDECREF(output);
return NULL;
}