I have a numpy array with a custom dtype:
a = np.zeros(100, dtype=np.dtype([('one',np.double),('two',np.int)]))
a['one']=np.arange(100)
a['two']=np.arange(100)*-1
I want to create a ctypes pointer that I can pass to a C library. The problem is that the C library expects just a pointer to a double array, the 'one' field.
I tried with: a['one'].ctypes.data_as(ctypes.POINTER(ctypes.c_double))
but it does not work, I believe because the C routine does not know what is the correct stride to go trough the array.
Would you have any suggestion, possibly without copying the array?
asked Jun 29, 2011 at 1:27
Andrea Zonca
8,83310 gold badges46 silver badges74 bronze badges
1 Answer 1
You are going to have to copy the data to a contiguous array.
one = np.ascontiguousarray(a['one'])
one.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
answered Jun 29, 2011 at 2:23
Robert Kern
13.5k3 gold badges37 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Karl Knechtel
This is because there is no way to tell the C function what the correct stride is, and no way to change the stride to what it's expecting (i.e., contiguous doubles) except to create data that's formatted as it expects.
Andrea Zonca
I was afraid of that...thank you, in principle if the C function would expect insted a structure of double+int would it work?
lang-py