How do I convert a Python list into a C array by using ctypes? How do I convert a Python list into a C array by using ctypes? python python

How do I convert a Python list into a C array by using ctypes?


The following code works on arbitrary lists:

import ctypespyarr = [1, 2, 3, 4]arr = (ctypes.c_int * len(pyarr))(*pyarr)


This is an explanation of the accepted answer.

ctypes.c_int * len(pyarr) creates an array (sequence) of type c_int of length 4 (python3, python 2). Since c_int is an object whose constructor takes one argument, (ctypes.c_int * len(pyarr)(*pyarr) does a one shot init of each c_int instance from pyarr. An easier to read form is:

pyarr = [1, 2, 3, 4]seq = ctypes.c_int * len(pyarr)arr = seq(*pyarr)

Use type function to see the difference between seq and arr.


From the ctypes tutorial:

>>> IntArray5 = c_int * 5>>> ia = IntArray5(5, 1, 7, 33, 99)