Call C code from Python
You can use ctypes
or cffi
to call C code from Python.
Using ctypes
-
Create a C Library
// example.c #include <stdio.h> void hello() { printf("Hello from C!\n"); }
-
Compile to Shared Library
gcc -shared -o libexample.so -fPIC example.c
-
Use in Python
import ctypes # Load the shared library lib = ctypes.CDLL('./libexample.so') # Call the function lib.hello()
Using cffi
-
Create a C Library
Same as above.
-
Compile to Shared Library
Same as above.
-
Use in Python
from cffi import FFI ffi = FFI() # Load the shared library lib = ffi.dlopen('./libexample.so') # Define the function prototype ffi.cdef('void hello();') # Call the function lib.hello()