User guide
NumPy User Guide, Release 1.9.0
5.3.6 Example Numpy ufunc with structured array dtype arguments
This example shows how to create a ufunc for a structured array dtype. For the example we show a trivial ufunc
for adding two arrays with dtype ‘u8,u8,u8’. The process is a bit different from the other examples since a call to
PyUFunc_FromFuncAndData doesn’t fully register ufuncs for custom dtypes and structured array dtypes. We need to
also call PyUFunc_RegisterLoopForDescr to finish setting up the ufunc.
We only give the C code as the setup.py file is exactly the same as the setup.py file in Example Numpy ufunc for one
dtype, except that the line
config.add_extension(’npufunc’, [’single_type_logit.c’])
is replaced with
config.add_extension(’npufunc’, [’add_triplet.c’])
The C file is given below.
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/npy_3kcompat.h"
/
*
*
add_triplet.c
*
This is the C code for creating your own
*
Numpy ufunc for a structured array dtype.
*
*
Details explaining the Python-C API can be found under
*
’Extending and Embedding’ and ’Python/C API’ at
*
docs.python.org .
*
/
static PyMethodDef StructUfuncTestMethods[] = {
{NULL, NULL, 0, NULL}
};
/
*
The loop definition must precede the PyMODINIT_FUNC.
*
/
static void add_uint64_triplet(char
**
args, npy_intp
*
dimensions,
npy_intp
*
steps, void
*
data)
{
npy_intp i;
npy_intp is1=steps[0];
npy_intp is2=steps[1];
npy_intp os=steps[2];
npy_intp n=dimensions[0];
uint64_t
*
x,
*
y,
*
z;
char
*
i1=args[0];
char
*
i2=args[1];
char
*
op=args[2];
for (i = 0; i < n; i++) {
x = (uint64_t
*
)i1;
y = (uint64_t
*
)i2;
94 Chapter 5. Using Numpy C-API