CFFI documentation
C Foreign Function Interface for Python. The goal is to provide a
convenient and reliable way to call compiled C code from Python using
interface declarations written in C.
Goals
The interface is based on LuaJIT’s FFI, and follows a few principles:
- The goal is to call C code from Python without learning a 3rd language:
existing alternatives require users to learn domain specific language
(Cython, SWIG) or API (ctypes). The CFFI design requires users to know
only C and Python, minimizing the extra bits of API that need to be learned.
- Keep all the Python-related logic in Python so that you don’t need to
write much C code (unlike CPython native C extensions).
- The preferred way is to work at the level of the API (Application
Programming Interface): the C compiler is called from the declarations
you write to validate and link to the C language constructs.
Alternatively, it is also possible to work at the ABI level
(Application Binary Interface), the way ctypes work.
However, on non-Windows platforms, C libraries typically
have a specified C API but not an ABI (e.g. they may
document a “struct” as having at least these fields, but maybe more).
- Try to be complete. For now some C99 constructs are not supported,
but all C89 should be, including macros (and including macro “abuses”,
which you can manually wrap in saner-looking C functions).
- Attempt to support both PyPy and CPython, with a reasonable path
for other Python implementations like IronPython and Jython.
- Note that this project is not about embedding executable C code in
Python, unlike Weave. This is about calling existing C libraries
from Python.
Get started by reading the overview.