Skip to content
Advertisement

How to pass Python list to C function using Cython

I am using a Raspberry Pi to interface with custom hardware connected to the GPIO. The controlling software is written in Python, and the interface to the custom hardware is written in C, as it is a much faster C implementation. I now need to start calling my C functions from my Python, and have recently been learning how to wrap C in Cython. I have got everything to work, except passing a Python list to a C function.

My custom hardware needs to be sent anywhere from 1 to 32 bytes, hence the use of an array.

The Cython tutorials and other references I have read online either are really simple, and do not include how to pass lists to C, use numpy, which I am not using, or use very complicated code examples that lack sufficient documentation for me to understand it properly.

What I have now are:

test.c

JavaScript

test.h

JavaScript

pytest.pyx

JavaScript

defns.pxd

JavaScript

Using the tutorials at cython.org, my getAll() and pop() functions work, but when I include the putAll() function (taken from the process_byte_data example code found at the link, under Unicode and passing strings > Accepting strings from Python code), I get this error:

JavaScript

Now, I have a way around this – combining up to 32 bytes into an int and passing as a long int, and then pulling it apart in C – but it is very ugly.

Also, I do not require Cython for any performance gains, other than that of using the C implemented library for interfacing with my custom hardware vs a Python implemented one.

Advertisement

Answer

ctypes is better suited to what you are trying to do.

For instance: (test.py)

JavaScript

Usage:

JavaScript

The above is for python 3 . If you’re running python 2 then you can substitute bytes for str, but the function is less flexible. In addition, be aware that create_string_buffer creates a C-string (adds an additional NUL character on the end of the string).

To compile the shared library you need to do the following:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement