I'm trying to develop C code that will be compiled to a DLL (or .SO for linux) with the purpose of processing some external input at high speed and returning the result to Python for follow-on processing.
My question is: what's the best way to regularly return values (at >1000s of time a second) from a C function for use in Python?
I created a test case as follows:
//dummy_function.c
#include <stdio.h>
#include <Windows.h>
__declspec(dllexport) int runme() {
int i;
for (i=1; i<= 500; i++) {
printf("int = %d \n", i);
Sleep(100); // Add some arbitrary delay for now
}
}
NB, I import Windows.h to use a dummy time delay (simulating my real-world problem). This code could run on unix using unistd.h instead (according to: What is the proper #include for the function 'sleep' in C?)
This code is then compiled into a .dll by
gcc -shared -o dummy_function.dll dummy_function.c
and imported in Python by:
import ctypes
libc = ctypes.CDLL('dummy_function.dll')
libc.runme() # Start running
When executing this Python code, it does print out the increasing integers. However, catching the printed output from C using Python and then processing it doesn't seem like a good way to do this (/not scalable for high speed).
Instead, I wonder if there's a way to more easily pass variables to Python from the DLL. I guess I don't want to use the return
function in C as this exits the function.
I've read about passing by reference in C, so wonder if this is compatible with ctypes. Could I define some memory location that the C code writes into, and the Python then polls this? Or better, some form of queue / buffer to avoid missing events?
Any advice would be greatly appreciated, thanks!