使用 ctypes 将字节 numpy 数组传递给 C 函数
Pass byte numpy array to C function using ctypes
我想使用 ctypes
将字节 numpy 数组传递给 C
函数。 C
函数需要 void *mem_address
所以我想按如下方式传递它:
lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5))
lst = np.asarray(lst).tobytes()
# Pass
lst.ctypes.data_as(ctypes.c_void_p)
这给出了错误 AttributeError: 'bytes' object has no attribute 'ctypes'
这意味着 ctypes
不处理 numpy。有解决方法吗?
lst
现在是 python bytes
对象,而不是 numpy
数组。这就是 .tobytes()
所做的。
为什么不做
lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5))
lst.ctypes.data_as(ctypes.c_void_p)
?
我什至不确定为什么当 c 指针是 32 位或 64 位时你试图转换为 8 位的字节。
lst = np.asarray(lst).tobytes()
生成一个普通的 bytes 对象([Python 3]: class bytes([source[, encoding[, errors]]]) 未被 ctypes.
另一方面,原始 lst 对象 ([SciPy]: numpy.ndarray) 是。因此,删除上面的代码行将修复错误。
我想使用 ctypes
将字节 numpy 数组传递给 C
函数。 C
函数需要 void *mem_address
所以我想按如下方式传递它:
lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5))
lst = np.asarray(lst).tobytes()
# Pass
lst.ctypes.data_as(ctypes.c_void_p)
这给出了错误 AttributeError: 'bytes' object has no attribute 'ctypes'
这意味着 ctypes
不处理 numpy。有解决方法吗?
lst
现在是 python bytes
对象,而不是 numpy
数组。这就是 .tobytes()
所做的。
为什么不做
lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5))
lst.ctypes.data_as(ctypes.c_void_p)
?
我什至不确定为什么当 c 指针是 32 位或 64 位时你试图转换为 8 位的字节。
lst = np.asarray(lst).tobytes()
生成一个普通的 bytes 对象([Python 3]: class bytes([source[, encoding[, errors]]]) 未被 ctypes.
另一方面,原始 lst 对象 ([SciPy]: numpy.ndarray) 是。因此,删除上面的代码行将修复错误。