Can't figure out how to do something using ctypes (and maybe struct?)

Peter Otten __peter__ at web.de
Sat Aug 11 04:54:54 EDT 2018


inhahe wrote:

> I need to make a list of instances of a Structure, then I need to make an
> instance of another Structure, one of the fields of which needs to be an
> arbitrary-length array of pointers to the instances in the list. How do I
> do that?
> 
> Just in case it helps, I'll include what I tried that didn't work:
> ------
> class NoteEvent(ctypes.Structure):
>   _fields_ = [('type', ctypes.c_int),
>               ('byteSize', ctypes.c_int),
>               ('deltaFrames', ctypes.c_int),
>               ('flags', ctypes.c_int),
>               ('noteLength', ctypes.c_int),
>               ('noteOffset', ctypes.c_int),
>               ('commandCode', ctypes.c_char),
>               ('noteNumber', ctypes.c_char),
>               ('velocity', ctypes.c_char)]
> 
> def mkVstEvents(events):
>   class Events(ctypes.Structure):
>     _fields_ = [('numEvents', ctypes.c_int),
>                 ('reserved', ctypes.c_int),
>                 ('eventspointerarray', ctypes.c_void_p * len(events))]
>   return Events(len(events), 0, tuple([ctypes.pointer(event) for event in
> events]))

...

> RuntimeError: (c_void_p_Array_1) <type 'exceptions.TypeError'>:
> incompatible types, LP_NoteEvent instance instead of c_void_p instance

Two things that you can try:

>                 ('eventspointerarray', ctypes.c_void_p * len(events))]

Either change c_void_p to POINTER(NoteEvent) like

https://stackoverflow.com/questions/7015487/ctypes-variable-length-structures

or cast the NoteEvent pointer to void *:

>   return Events(len(events), 0, tuple([ctypes.pointer(event) for event in
> events]))

... cast(pointer(event), c_void_p) ...





More information about the Python-list mailing list