How to use NumPy array with ctypes?

Framester picture Framester · Jul 7, 2010 · Viewed 22k times · Source

I am still writing on a python interface for my c code with ctypes. Today I substituted my file reading function with a python version, which was programmed by somebody else using NumPy. The 'old' c version was called with a byref(p_data) while p_data=PFloat() (see below). The main function takes the p_data.

Old file reading:

p_data=POINTER(c_float)
foo.read(filename,byref(p_data))
result=foo.pymain(p_data)

The python file reading function, on the other hand, returns a NumPy array. My question now is:

How do I convert a NumPy array to POINTER(c_float)?

I googled but only found the other way around: C arrays through ctypes accessed as NumPy arrays and things I didn't understand: C-Types Foreign Function Interface (numpy.ctypeslib)

[update] corrected a mistake in the example code

Answer

llasram picture llasram · Sep 8, 2010

Your code looks like it has some confusion in it -- ctypes.POINTER() creates a new ctypes pointer class, not a ctypes instance. Anyway, the easiest way to pass a NumPy array to ctypes code is to use the numpy.ndarray's ctypes attribute's data_as method. Just make sure the underlying data is the right type first. For example:

import ctypes
import numpy
c_float_p = ctypes.POINTER(ctypes.c_float)
data = numpy.array([[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]])
data = data.astype(numpy.float32)
data_p = data.ctypes.data_as(c_float_p)