我有以下 ctypes 数组:
data = (ctypes.c_uint * 100)()
我想创建一个 numpy 数组np_data
包含来自 ctypes 数组数据的整数值(ctypes 数组显然稍后会填充值)
我看到numpy中有一个ctypes接口(https://docs.scipy.org/doc/numpy/reference/ generated/numpy.ndarray.ctypes.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ctypes.html)但据我了解,这只是从 numpy 数组中获取 ctypes,而不是相反。
我明明可以穿越data
并填充np_data
一项一项地排列项目,但我想知道是否有一种更有效/直接的方法来完成这项任务。
你可以使用[NumPy]: numpy.ctypeslib.as_array(obj, shape=None) https://numpy.org/doc/stable/reference/routines.ctypeslib.html#numpy.ctypeslib.as_array.
>>> import ctypes as ct
>>> import numpy as np
>>>
>>>
>>> CUIntArr10 = ctypes.c_uint * 10
>>>
>>> ui10 = CUIntArr10(*range(10, 0, -1))
>>>
>>> [e for e in ui10] # The ctypes array
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>
>>> np_arr = np.ctypeslib.as_array(ui10)
>>> np_arr # And the np one
array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], dtype=uint32)
没有到达特定的代码行(我也没有测试我的假设),但我有一种感觉,内容复制是由单个完成的memcpy调用,这将比“手动”执行操作要快得多Python.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)