Friday, June 29, 2012

python, numpy, c and ctypes

so, it is very easy for combining c and python together. 
and it is also very confusing because there are alot of ways to do such same task

for instance, there are boost, swig, sip and shiboken
i think it would better to standarize the interface and integrate it into new python 3000
anyway, here are some collections of how to do such 

1. memory address -> numpy array: 

ctypes_array = (ctypes.c_char * MEM_SIZE).from_address(pointer) 
numpy_array = numpy.frombuffer(ctypes_array, dtype=numpy.float64)
numpy_array

2. numpy array -> memory address
pointer = ndarray.__array_interface__['data'][0]

3. numpy array -> ctype pointer, which is already wrapped, not a simple address 

data = numpy.array([[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]])
data = data.astype(numpy.float32)
c_float_p = ctypes.POINTER(ctypes.c_float)
data_p = data.ctypes.data_as(c_float_p)
then if we want to access the data at this address, use the function contents()

actually all these can be done in a standard numpy way, pls refer to :
C-Types Foreign Function Interface (numpy.ctypeslib)

No comments:

Post a Comment