4

I have a python callback function which accepts 2 arguments: a pointer to a chunk of memory, and the length of the memory chunk.

def my_callback( buf, len):
    """ buf is of type POINTER(c_ubyte), len is of type c_uint"""

Inside the callback function, i'd like to first convert the memory chunk to ctypes array. I know it can be done by creating a new ctypes array and copy over all the data from the memory chunk.

def my_callback( buf, len):
    """ buf is of type POINTER(c_ubyte), len is of type c_uint"""
    temp_array = (c_ubyte * len)(*[buf[n] for n in range(len)])

But by this way memory copy is needed. My question is if there is any way to just cast the ctypes pointer to array without memory copying?

Thanks in advance for any answers or hints.

Minghao Ni
  • 41
  • 4
  • possible duplicate of [Pointers and arrays in Python ctypes](http://stackoverflow.com/questions/1363163/pointers-and-arrays-in-python-ctypes) – Peter Wood Sep 18 '15 at 06:43
  • See [Type conversions](https://docs.python.org/2/library/ctypes.html#type-conversions) in the documentation and [`ctypes.cast`](https://docs.python.org/2/library/ctypes.html#ctypes.cast) – Peter Wood Sep 18 '15 at 06:46
  • Array can be casted to pointer. But seems the reverse cast is illegal. Got error: TypeError: cast() argument 2 must be a pointer type, not c_uint_Array_1 – Minghao Ni Sep 18 '15 at 09:23
  • 5
    A C array is a homogeneous aggregate type, not a pointer type. The associated buffer of an array is the block of elements, while the associated buffer of a pointer is the 4 or 8 bytes of a memory address. Just cast to a pointer to the array and then dereference it, e.g. `buf = cast(pbuf, POINTER(c_ubyte * len))[0]`. – Eryk Sun Sep 18 '15 at 11:30
  • BTW, a ctypes array can be cast to a pointer because `ctypes.cast` is implemented as a C function call, for which an array argument degenerates to a pointer. In other words, in a C function an array argument becomes a pointer that points at the array's first element and has the size of a memory address (4 or 8 bytes). – Eryk Sun Sep 18 '15 at 11:40
  • Thanks goes to @eryksun, This casting solved my problem. – Minghao Ni Sep 21 '15 at 01:39
  • Possible duplicate of [Python & Ctypes: Passing a struct to a function as a pointer to get back data](http://stackoverflow.com/questions/4351721/python-ctypes-passing-a-struct-to-a-function-as-a-pointer-to-get-back-data) – maazza Dec 15 '15 at 12:39
  • Did you solve your problem yet ? – tauseef_CuriousGuy Sep 01 '17 at 09:31

0 Answers0