简体   繁体   中英

Problem converting numpy array to ctypes array

I'm having a problem converting a numpy array to a ctypes array. I don't get any errors or exceptions, but the ctypes array is completely different from the original array.

def convarray(x):
    arr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64) )
    print(arr[0], arr[1], arr[2])
    print(x.shape, x.dtype, x)
    ...

The result of the print statements is:

8 399 1099526307842
(958150,) uint64 [ 8 8 8... 92 94 96]

As you can see, of the first three elements, only one is correct.

Why is this happening?

I am using Numpy 1.21.0 with Python 3.9.2

I discovered what the problem was: the array being passed as x was derived by slicing from a 2d array, and thus its underlying data was 2 dimensional as well. Setting x = x.copy() solved the problem by creating a new array with 1 dimensional data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM