Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

c

ctypes

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?

like image 906
No One in Particular Avatar asked Nov 10 '10 14:11

No One in Particular


People also ask

How do I turn a list into a array in Python?

To convert a list to array in Python, use the np. array() method. The np. array() is a numpy library function that takes a list as an argument and returns an array containing all the list elements.

What is Ctypes array?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Which function can be used to convert an array into a list in Python?

We can use numpy ndarray tolist() function to convert the array to a list. If the array is multi-dimensional, a nested list is returned. For one-dimensional array, a list with the array elements is returned.


2 Answers

The following code works on arbitrary lists:

import ctypes pyarr = [1, 2, 3, 4] arr = (ctypes.c_int * len(pyarr))(*pyarr) 
like image 62
Gabi Purcaru Avatar answered Oct 20 '22 13:10

Gabi Purcaru


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.

like image 35
akhan Avatar answered Oct 20 '22 15:10

akhan