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

No One in Particular picture No One in Particular · Nov 10, 2010 · Viewed 49.7k times · Source

If I have the follow 2 sets of code, how do I glue them together?

void
c_function(void *ptr) {
    int i;

    for (i = 0; i < 10; i++) {
        printf("%p", ptr[i]);
    }

    return;
}


def python_routine(y):
    x = []
    for e in y:
        x.append(e)

How can I call the c_function with a contiguous list of elements in x? I tried to cast x to a c_void_p, but that didn't work.

I also tried to use something like

x = c_void_p * 10 
for e in y:
    x[i] = e

but this gets a syntax error.

The C code clearly wants the address of an array. How do I get this to happen?

Answer

Gabi Purcaru picture Gabi Purcaru · Nov 10, 2010

The following code works on arbitrary lists:

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