User guide

NumPy User Guide, Release 1.9.0
not the striding pattern matches a standard C or Fortran one can be tested Using PyArray_ISCONTIGUOUS (obj)
and PyArray_ISFORTRAN (obj) respectively. Most third-party libraries expect contiguous arrays. But, often it is
not difficult to support general-purpose striding. I encourage you to use the striding information in your own code
whenever possible, and reserve single-segment requirements for wrapping third-party code. Using the striding infor-
mation provided with the ndarray rather than requiring a contiguous striding reduces copying that otherwise must be
made.
5.1.5 Example
The following example shows how you might write a wrapper that accepts two input arguments (that will be converted
to an array) and an output argument (that must be an array). The function returns None and updates the output array.
static PyObject
*
example_wrapper(PyObject
*
dummy, PyObject
*
args)
{
PyObject
*
arg1=NULL,
*
arg2=NULL,
*
out=NULL;
PyObject
*
arr1=NULL,
*
arr2=NULL,
*
oarr=NULL;
if (!PyArg_ParseTuple(args, "OOO!", &arg1, &arg2,
&PyArray_Type, &out)) return NULL;
arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_IN_ARRAY);
if (arr1 == NULL) return NULL;
arr2 = PyArray_FROM_OTF(arg2, NPY_DOUBLE, NPY_IN_ARRAY);
if (arr2 == NULL) goto fail;
oarr = PyArray_FROM_OTF(out, NPY_DOUBLE, NPY_INOUT_ARRAY);
if (oarr == NULL) goto fail;
/
*
code that makes use of arguments
*
/
/
*
You will probably need at least
nd = PyArray_NDIM(<..>) -- number of dimensions
dims = PyArray_DIMS(<..>) -- npy_intp array of length nd
showing length in each dim.
dptr = (double
*
)PyArray_DATA(<..>) -- pointer to data.
If an error occurs goto fail.
*
/
Py_DECREF(arr1);
Py_DECREF(arr2);
Py_DECREF(oarr);
Py_INCREF(Py_None);
return Py_None;
fail:
Py_XDECREF(arr1);
Py_XDECREF(arr2);
PyArray_XDECREF_ERR(oarr);
return NULL;
}
5.2 Using Python as glue
There is no conversation more boring than the one where everybody
60 Chapter 5. Using Numpy C-API