User guide
NumPy User Guide, Release 1.9.0
Using an ndpointer class in the argtypes method can make it significantly safer to call a C-function using ctypes and
the data- area of an ndarray. You may still want to wrap the function in an additional Python wrapper to make it
user-friendly (hiding some obvious arguments and making some arguments output arguments). In this process, the
requires function in NumPy may be useful to return the right kind of array from a given input.
Complete example
In this example, I will show how the addition function and the filter function implemented previously using the other
approaches can be implemented using ctypes. First, the C-code which implements the algorithms contains the func-
tions zadd, dadd, sadd, cadd, and dfilter2d. The zadd function is:
/
*
Add arrays of contiguous data
*
/
typedef struct {double real; double imag;} cdouble;
typedef struct {float real; float imag;} cfloat;
void zadd(cdouble
*
a, cdouble
*
b, cdouble
*
c, long n)
{
while (n--) {
c->real = a->real + b->real;
c->imag = a->imag + b->imag;
a++; b++; c++;
}
}
with similar code for cadd, dadd, and sadd that handles complex float, double, and float data-types, respectively:
void cadd(cfloat
*
a, cfloat
*
b, cfloat
*
c, long n)
{
while (n--) {
c->real = a->real + b->real;
c->imag = a->imag + b->imag;
a++; b++; c++;
}
}
void dadd(double
*
a, double
*
b, double
*
c, long n)
{
while (n--) {
*
c++ =
*
a++ +
*
b++;
}
}
void sadd(float
*
a, float
*
b, float
*
c, long n)
{
while (n--) {
*
c++ =
*
a++ +
*
b++;
}
}
The code.c file also contains the function dfilter2d:
/
*
Assumes b is contiguous and
a has strides that are multiples of sizeof(double)
*
/
void
dfilter2d(double
*
a, double
*
b, int
*
astrides, int
*
dims)
{
int i, j, M, N, S0, S1;
int r, c, rm1, rp1, cp1, cm1;
M = dims[0]; N = dims[1];
5.2. Using Python as glue 75