Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

python - How to use NumPy array with ctypes?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...