如何在ctype中使用NumPy数组?

时间:2022-07-20 21:43:31

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 usind 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.

我还在用ctype编写我的c代码的python接口。今天我用python版本替换了我的文件读取函数,python版本是由别人用NumPy编写的。“old”c版本使用了byref(p_data),而p_data=PFloat()(见下文)。主函数接受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:

另一方面,python文件读取函数返回一个NumPy数组。现在我的问题是:

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

如何将NumPy数组转换为指针(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)

我在谷歌上搜索了一下,但只找到了另一种方法:通过ctype访问的C数组作为NumPy数组以及一些我不理解的东西:C类型外函数接口(numpi .ctypeslib)

[update] corrected a mistake in the example code

[更新]纠正示例代码中的错误

1 个解决方案

#1


17  

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:

您的代码看起来有点混乱——ctypes. pointer()创建了一个新的ctypes指针类,而不是一个ctypes实例。无论如何,将NumPy数组传递给ctypes代码的最简单的方法是使用NumPy。ndarray的ctypes属性的data_as方法。首先要确保底层数据是正确的类型。例如:

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)

#1


17  

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:

您的代码看起来有点混乱——ctypes. pointer()创建了一个新的ctypes指针类,而不是一个ctypes实例。无论如何,将NumPy数组传递给ctypes代码的最简单的方法是使用NumPy。ndarray的ctypes属性的data_as方法。首先要确保底层数据是正确的类型。例如:

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)