Pointers and arrays in Python ctypes Pointers and arrays in Python ctypes python python

Pointers and arrays in Python ctypes


You can cast with the cast function :)

>>> import ctypes>>> x = (ctypes.c_ulong*5)()>>> x<__main__.c_ulong_Array_5 object at 0x00C2DB20>>>> ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong))<__main__.LP_c_ulong object at 0x0119FD00>>>> 


You can cast the result, but ctypes allows you to use an array in place of a pointer, directly. The issue is the byref in your code (which would be the equivalent of a pointer to a pointer):

So instead of:

cresult = (c_ulong * num)()err = self.c_read_block(addr, byref(cresult), num)

try:

cresult = (c_ulong * num)()err = self.c_read_block(addr, cresult, num)


A more compact version of the solution from the first answer:

>>> from ctypes import *>>> x = (c_ulong*5)()>>> x<__main__.c_ulong_Array_5 object at 0x7f96852bd0e0>>>> cast(x, POINTER(c_ulong))<__main__.LP_c_ulong object at 0x7f96852bd170>