I am writing a code, where I create an numpy array of pointers. They point to other arrays.
I can succesfully (no exception is generated) store a pointer inside one element of the array-of-pointers. But I cannot re-convert this pointer to a numpy array.
The problem specifically appears when pointers are stored in an numpy array of pointers. I can succesfully store and retrive an array when I store the pointer in a normal pyhon variable.
Note that I cannot just create a python list of pointers because of performances reasons.
this code works:
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)
and v
will return the initial array set in ic
.
this code does not work:
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))
The last line will give the following exception:
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
Question: how do I store and retrive a numpy-array from/to a numpy-array of pointers?