Numpy:从一系列指针中检索阵列



我正在编写一个代码,其中我创建了一个数量的指针。他们指向其他数组。

我可以(不例外)将指针存储在计算机数组的一个元素中。但是我无法重新转换为numpy数组的指针。

当指针存储在数量的指针阵列中时,该问题专门出现。当我将指针存储在普通的Pyhon变量中时,我可以成功地存储和检索数组。

请注意,由于表现原因,我不能仅创建指针的python列表。

此代码有效:

import numpy, ctypes
ic = numpy.array([[1,2],[3,4]],dtype=numpy.int32)
pointer = ic.__array_interface__['data'][0]
v = numpy.ctypeslib.as_array(ctypes.cast(pointer,ctypes.POINTER(ctypes.c_int)),shape=(2,2))
print(v)

v将返回ic中的初始数组集。

此代码不起作用:

import numpy, ctypes
ic = numpy.array([[1,2],[3,4]],dtype=numpy.int32)
pointers = numpy.zeros(5, dtype=ctypes.POINTER(ctypes.c_int))
pointers[0] = ic.__array_interface__['data'][0]
numpy.ctypeslib.as_array(ctypes.cast(pointers[0],ctypes.POINTER(ctypes.c_int)),shape=(2,2))

最后一行将给出以下例外:

File "/opt/intel/intelpython3/lib/python3.5/ctypes/__init__.py", line 484, in cast
return _cast(obj, obj, typ)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

问题:如何存储和检索/到指示器的numpy阵列?

索引数组返回 np.int32对象,而不是本机Python int

In [118]: type(pointer)
Out[118]: int
In [119]: type(pointers[0])
Out[119]: numpy.int32

使用item提取INT:

In [120]: type(pointers[0].item())
Out[120]: int

您也可以首先将数组转换为列表

In [121]: type(pointers.tolist()[0])
Out[121]: int

pointers当您构造时,它是 np.int32 dtype

In [123]: pointers = numpy.zeros(5, dtype=ctypes.POINTER(ctypes.c_int))
In [124]: pointers.dtype
Out[124]: dtype('int32')

或者使对象dtype数组

In [125]: pointers = numpy.zeros(5, dtype=object)
In [126]: pointers[0] = pointer
In [127]: pointers
Out[127]: array([157379928, 0, 0, 0, 0], dtype=object)
In [128]: type(pointers[0])
Out[128]: int

最新更新