cffi
- Python course
- Expert
- Lesson 22/47
- 5 min
Learn to call C code with cffi.
What is cffi?
cffi (C Foreign Function Interface) is an alternative to ctypes. It lets you write C header declarations directly in Python.
You create an FFI object, declare C signatures with ffi.cdef, then load the library with ffi.dlopen. Two advantages over ctypes: signatures are written in C syntax (more natural) and type checking happens at parse time. cffi is also faster than ctypes on PyPy.
C code with cffi
Using cffi takes three steps: create FFI(), declare the signature with ffi.cdef('int abs(int);'), load the library with lib = ffi.dlopen(None).
You then call the function with lib.abs(-9). Since the signature is in C syntax it is easy to copy from header files. Errors in cdef are caught at parse time; there are no runtime crashes like with ctypes. This makes cffi safer for large C APIs.
Practice Call strlen with cffi
Import with from cffi import FFI. Create an FFI() object. Declare the signature with ffi.cdef('size_t strlen(const char*);'). Load the library with ffi.dlopen(None). Print the result of lib.strlen(b"dunya").
Starter code
# call a C function with cffi
# print the resultSample solution
from cffi import FFI
ffi = FFI()
ffi.cdef("size_t strlen(const char*);")
lib = ffi.dlopen(None)
print(lib.strlen(b"dunya"))Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match cffi concepts
| Term | Meaning |
|---|---|
FFI |
Interface object |
cdef |
C declaration |
dlopen |
Loads a library |
cffi |
ctypes alternative |
2 What does cffi provide?
from cffi import FFI
ffi = FFI()
ffi.cdef('int abs(int);')- Running SQL from Python
- Writing C declarations in Python Correct answer
- Generating web pages
- File compression
Explanation: answer: writing C declarations in Python. cffi is designed for C interfaces.
3 Complete the cffi call
ffi = FFI()
ffi.____('int abs(int);')
ffi = FFI()
ffi.cdef('int abs(int);')
Explanation: cdef declares a C signature.