Call C code from Python
~2 mins read
You can use ctypes
or cffi
to call C code from Python.
Using ctypes
-
Create a C Library
1 2 3 4 5 6
// example.c #include <stdio.h> void hello() { printf("Hello from C!\n"); }
-
Compile to Shared Library
1
gcc -shared -o libexample.so -fPIC example.c
-
Use in Python
1 2 3 4 5 6 7
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
1 2 3 4 5 6 7 8 9 10 11 12
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()