User guide
NumPy User Guide, Release 1.9.0
lib.dfilter2d.restype=None
lib.dfilter2d.argtypes = [N.ctypeslib.ndpointer(float, ndim=2,
flags=’aligned’),
N.ctypeslib.ndpointer(float, ndim=2,
flags=’aligned, contiguous,’\
’writeable’),
ctypes.POINTER(N.ctypeslib.c_intp),
ctypes.POINTER(N.ctypeslib.c_intp)]
Next, define a simple selection function that chooses which addition function to call in the shared library based on the
data-type:
def select(dtype):
if dtype.char in [’?bBhHf’]:
return lib.sadd, single
elif dtype.char in [’F’]:
return lib.cadd, csingle
elif dtype.char in [’DG’]:
return lib.zadd, complex
else:
return lib.dadd, float
return func, ntype
Finally, the two functions to be exported by the interface can be written simply as:
def add(a, b):
requires = [’CONTIGUOUS’, ’ALIGNED’]
a = N.asanyarray(a)
func, dtype = select(a.dtype)
a = N.require(a, dtype, requires)
b = N.require(b, dtype, requires)
c = N.empty_like(a)
func(a,b,c,a.size)
return c
and:
def filter2d(a):
a = N.require(a, float, [’ALIGNED’])
b = N.zeros_like(a)
lib.dfilter2d(a, b, a.ctypes.strides, a.ctypes.shape)
return b
Conclusion
Using ctypes is a powerful way to connect Python with arbitrary C-code. It’s advantages for extending Python include
• clean separation of C-code from Python code
– no need to learn a new syntax except Python and C
– allows re-use of C-code
– functionality in shared libraries written for other purposes can be obtained with a simple Python wrapper
and search for the library.
• easy integration with NumPy through the ctypes attribute
• full argument checking with the ndpointer class factory
5.2. Using Python as glue 77