ctypes and ndpointer
Hello all Just a quick note on the ndpointer function that Travis recently added to NumPy (thanks Travis!). When wrapping functions with ctypes, one can specify the argument types of the function. ctypes then checks that the parameters are valid before invoking the C function. This is described here in detail: http://docs.python.org/dev/lib/ctypes-specifying-required-argument-types.htm l The argtypes list is optional, and I think previously Travis suggested not specifying the argtypes because it would require one to write something like this: bar.argtypes = [POINTER(c_double)] x = N.array([...]) bar(x.data_as(POINTER(c_double)) instead of simply: bar(x) What ndpointer allows one to do is to build classes with a from_param method that knows about the details of ndarrays and how to convert them to something that ctypes can send to a C function. For example, suppose you have the following function: void bar(int* data, double x); You know that bar expects a 20x30 array of big-endian integers in Fortran order. You can make sure it gets only this kind of array by doing: _foolib = N.ctypes_load_library('foolib_', '.') bar = _foolib.bar bar.restype = None p = N.ndpointer(dtype='>i4', ndim=2, shape=(20,30), flags='FORTRAN') bar.argtypes = [p, ctypes.c_double] x = N.zeros((20,30),dtype='>i4',order='F') bar(x, 123.0) If you want your function to accept any kind of ndarray, you can do: bar.argtypes = [N.ndpointer(),...] In this case it will probably still make sense to wrap the C function in a Python function that also passes the .ctypes.strides and .ctypes.shape of the array. Cheers, Albert P.S. Sidebar: do we want these ctypes functions in the top-level namespace? Maybe not. Also, I'm starting to wonder whether ctypes_load_library deserves to exist or whether we should hear from the ctypes guys if there is a better way to accomplish what it does (which is to make it easy to load a shared library/DLL/dylib relative to some file in your module on any platform).
Albert Strasheim wrote:
P.S. Sidebar: do we want these ctypes functions in the top-level namespace? Maybe not. Also, I'm starting to wonder whether ctypes_load_library deserves to exist or whether we should hear from the ctypes guys if there is a better way to accomplish what it does (which is to make it easy to load a shared library/DLL/dylib relative to some file in your module on any platform).
I'm happy to move them from the top-level name-space to something else prior to 1.0 final. It's probably a good idea. -Travis
participants (2)
-
Albert Strasheim
-
Travis Oliphant