Link Search Menu Expand Document

Use C code with cffi

In this example, we demonstrate how to use C code from Python, thanks to cffi. This package allows Python to act as a wrapper for code written in C.

For instance, we can write a function in C and expose it so that it can be called from Python. This approach is useful when we want the speed of C but the simplicity of Python. In fact, many Python packages, such as numpy, are implemented in C under the hood.

First, we define a C code. This is the code we want to call from Python. We create a function to determine if a number is prime.

// 37_c_code.c
#include <stdbool.h>
#include <math.h>

bool is_prime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;

    int limit = sqrt(n);
    for (int i = 5; i <= limit; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    return true;
}

Next, we use cffi. First, we must compile our C code so that it can be used by Python. This step only needs to be done once. Note the compile step.

import cffi
import os

if not os.path.exists("mylib.o"):
    ffi = cffi.FFI()
    ffi.cdef("bool is_prime(int n);")
    ffi.set_source(
        "_mylib",
        '#include "37_c_code.c"')
    ffi.compile()

Once compiled, we can import the library and use is_prime. The code that runs underneath is compiled C code, but you are actually using Python code.

import _mylib
number = 777
prime = _mylib.lib.is_prime(number)
print(f"The number {number} is{' not' if not prime else ''} prime.")

✏️ Exercises:

  • Create a C function are_primes that, given a list of numbers, returns another list of booleans indicating whether each of the input numbers is prime. Call this function from Python.