如何在ctypes中使用NumPy数组? [英] How to use NumPy array with ctypes?
问题描述
我仍在用ctypes编写C代码的python接口。今天,我用python版本代替了文件读取功能,该版本是由其他人使用NumPy编程的。旧版本的c版本使用 byref(p_data)
调用,而 p_data = PFloat()
调用(请参见下文) 。主要功能采用 p_data
。
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
.
旧文件读取:
p_data=POINTER(c_float)
foo.read(filename,byref(p_data))
result=foo.pymain(p_data)
另一方面,python文件读取功能返回一个NumPy数组。现在我的问题是:
The python file reading function, on the other hand, returns a NumPy array. My question now is:
我如何将NumPy数组转换为 POINTER(c_float)
?
How do I convert a NumPy array to POINTER(c_float)
?
我用Google搜索,但发现却只有相反的方式:通过作为NumPy数组访问的ctypes的C数组和我不理解的东西: C类外部函数接口(numpy.ctypeslib)
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
推荐答案
您的代码看起来有些混乱- ctypes.POINTER()
创建一个新的ctypes指针 class ,而不是ctypes实例。无论如何,将NumPy数组传递给ctypes代码的最简单方法是使用 numpy.ndarray
的 ctypes
属性 data_as
方法。只需确保基础数据首先是正确的类型。例如:
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)
这篇关于如何在ctypes中使用NumPy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!