Numpy:从指针数组中检索数组

Numpy: Retriving an array from an array of pointers

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

我可以成功地(没有产生异常)在指针数组的一个元素中存储一个指针。但我无法将此指针重新转换为 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将return设置在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 数组from/to一个 numpy 指针数组?

索引数组 returns 一个 np.int32 对象,而不是原生对象 Python int:

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

使用item提取整数:

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