如何使用带有ctypes的NumPy数组?

Fra*_*ter 9 python ctypes numpy

我仍在使用ctypes在我的c代码的python接口上编写.今天我用python版本替换了我的文件读取功能,这是由其他人使用NumPy编写的.使用byref(p_data)调用'old'c版本,而p_data = PFloat()(见下文).main函数采用p_data.

旧文件阅读:

p_data=POINTER(c_float)
foo.read(filename,byref(p_data))
result=foo.pymain(p_data)
Run Code Online (Sandbox Code Playgroud)

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

如何将NumPy数组转换为POINTER(c_float)?

我用谷歌搜索,但只发现相反的方式:C数组通过ctypes访问为NumPy数组和我不理解的东西:C类型外部函数接口(numpy.ctypeslib)

[update] 更正了示例代码中的错误

lla*_*ram 22

你的代码看起来有些混乱 - ctypes.POINTER()创建一个新的ctypes指针,而不是一个ctypes实例.无论如何,将NumPy数组传递给ctypes代码的最简单方法是使用numpy.ndarray's ctypes属性的data_as方法.只需先确保基础数据是正确的类型.例如:

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)
Run Code Online (Sandbox Code Playgroud)


Mar*_*hke 10

使用np.ndarraysctypes参数

更可取的方法是使用ndpointer,如numpy-docs 中所述

这种方法比使用例如 POINTER(c_double) 更灵活,因为可以指定几个限制,这些限制在调用 ctypes 函数时进行验证。这些包括数据类型、维数、形状和标志。如果给定的数组不满足指定的限制,则会引发 TypeError。

最小的、可重现的示例

从 python调用memcpy。最终libc.so.6需要调整标准 C 库的文件名。

import ctypes
import numpy as np

n_bytes_f64 = 8
nrows = 2
ncols = 5

clib = ctypes.cdll.LoadLibrary("libc.so.6")

clib.memcpy.argtypes = [
    np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
    np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'),
    ctypes.c_size_t]
clib.memcpy.restype = ctypes.c_void_p

arr_from = np.arange(nrows * ncols).astype(np.float64)
arr_to = np.empty(shape=(nrows, ncols), dtype=np.float64)

print('arr_from:', arr_from)
print('arr_to:', arr_to)

print('\ncalling clib.memcpy ...\n')
clib.memcpy(arr_to, arr_from, nrows * ncols * n_bytes_f64)

print('arr_from:', arr_from)
print('arr_to:', arr_to)
Run Code Online (Sandbox Code Playgroud)

输出

arr_from: [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
arr_to: [[0.0e+000 4.9e-324 9.9e-324 1.5e-323 2.0e-323]
 [2.5e-323 3.0e-323 3.5e-323 4.0e-323 4.4e-323]]

calling clib.memcpy ...

arr_from: [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
arr_to: [[0. 1. 2. 3. 4.]
 [5. 6. 7. 8. 9.]]
Run Code Online (Sandbox Code Playgroud)

如果您将 的ndim=1/2参数修改为ndpointer与 的尺寸不一致arr_from/arr_to,则代码将失败并显示ArgumentError

由于这个问题的标题很笼统,...

np.ndarrayctypes.c_void_p结果构造 a

最小的、可重现的示例

在下面的示例中,一些内存由malloc分配,并由memset填充为 0 。然后构造一个 numpy 数组,以访问该内存。当然会发生一些所有权问题,因为python不会释放在c中分配的内存。为了避免内存泄漏,必须通过 ctypes 再次释放分配的内存。该复制方法可用于np.ndarray收购的所有权

import ctypes
import numpy as np

n_bytes_int = 4
size = 7

clib = ctypes.cdll.LoadLibrary("libc.so.6")

clib.malloc.argtypes = [ctypes.c_size_t]
clib.malloc.restype = ctypes.c_void_p

clib.memset.argtypes = [
    ctypes.c_void_p,
    ctypes.c_int,
    ctypes.c_size_t]
clib.memset.restype = np.ctypeslib.ndpointer(
    dtype=np.int32, ndim=1, flags='C_CONTIGUOUS')

clib.free.argtypes = [ctypes.c_void_p]
clib.free.restype = ctypes.c_void_p


pntr = clib.malloc(size * n_bytes_int)
ndpntr = clib.memset(pntr, 0, size * n_bytes_int)
print(type(ndpntr))
ctypes_pntr = ctypes.cast(ndpntr, ctypes.POINTER(ctypes.c_int))
print(type(ctypes_pntr))
print()
arr_noowner = np.ctypeslib.as_array(ctypes_pntr, shape=(size,))
arr_owner = np.ctypeslib.as_array(ctypes_pntr, shape=(size,)).copy()
# arr_owner = arr_noowner.copy()


print('arr_noowner (at {:}): {:}'.format(arr_noowner.ctypes.data, arr_noowner))
print('arr_owner (at {:}): {:}'.format(arr_owner.ctypes.data, arr_owner))

print('\nfree allocated memory again ...\n')
_ = clib.free(pntr)

print('arr_noowner (at {:}): {:}'.format(arr_noowner.ctypes.data, arr_noowner))
print('arr_owner (at {:}): {:}'.format(arr_owner.ctypes.data, arr_owner))

print('\njust for fun: free some python-memory ...\n')
_ = clib.free(arr_owner.ctypes.data_as(ctypes.c_void_p))

print('arr_noowner (at {:}): {:}'.format(arr_noowner.ctypes.data, arr_noowner))
print('arr_owner (at {:}): {:}'.format(arr_owner.ctypes.data, arr_owner))
Run Code Online (Sandbox Code Playgroud)

输出

<class 'numpy.ctypeslib.ndpointer_<i4_1d_C_CONTIGUOUS'>
<class '__main__.LP_c_int'>

arr_noowner (at 104719884831376): [0 0 0 0 0 0 0]
arr_owner (at 104719884827744): [0 0 0 0 0 0 0]

free allocated memory again ...

arr_noowner (at 104719884831376): [ -7687536     24381 -28516336     24381         0         0         0]
arr_owner (at 104719884827744): [0 0 0 0 0 0 0]

just for fun: free some python-memory ...

arr_noowner (at 104719884831376): [ -7687536     24381 -28516336     24381         0         0         0]
arr_owner (at 104719884827744): [ -7779696     24381 -28516336     24381         0         0         0]
Run Code Online (Sandbox Code Playgroud)