Foreign Function Interface for Python calling C code.
npx @tessl/cli install tessl/pypi-cffi@1.17.00
# CFFI
1
2
C Foreign Function Interface for Python calling C code. CFFI provides a way to interface with C libraries from Python without requiring extensive knowledge of Python C extension development, offering both ABI (Application Binary Interface) and API modes for different use cases.
3
4
## Package Information
5
6
- **Package Name**: cffi
7
- **Language**: Python
8
- **Installation**: `pip install cffi`
9
10
## Core Imports
11
12
```python
13
import cffi
14
```
15
16
Most common usage pattern:
17
18
```python
19
from cffi import FFI
20
```
21
22
## Basic Usage
23
24
```python
25
from cffi import FFI
26
27
# Create FFI instance
28
ffi = FFI()
29
30
# Define C declarations
31
ffi.cdef("""
32
int printf(const char *format, ...);
33
""")
34
35
# Load C library
36
C = ffi.dlopen(None) # Load C standard library
37
38
# Call C function
39
C.printf(b"Hello, World!\n")
40
41
# Create C data structures
42
p = ffi.new("int *")
43
p[0] = 42
44
print(p[0]) # 42
45
```
46
47
## Architecture
48
49
CFFI operates on a clear separation between declaration and implementation:
50
51
- **FFI Instance**: Main interface managing C declarations, type system, and backend
52
- **C Definitions**: Parsed C declarations stored in the FFI instance
53
- **Dynamic Libraries**: Loaded C libraries providing actual function implementations
54
- **Type System**: Complete C type representation with Python bindings
55
- **Memory Management**: Automatic garbage collection with manual control options
56
- **Backend**: Pluggable backend system (default: `_cffi_backend` C extension)
57
58
## Capabilities
59
60
### Core FFI Operations
61
62
Fundamental FFI functionality including instance creation, C code declaration parsing, and dynamic library loading. These operations form the foundation of all CFFI usage.
63
64
```python { .api }
65
class FFI:
66
def __init__(self, backend=None): ...
67
def cdef(self, csource, override=False, packed=False, pack=None): ...
68
def dlopen(self, name, flags=0): ...
69
def dlclose(self, lib): ...
70
def verify(self, source='', tmpdir=None, **kwargs): ...
71
```
72
73
[Core FFI Operations](./core-ffi.md)
74
75
### Memory Management
76
77
C memory allocation, deallocation, garbage collection, and address operations. CFFI provides automatic memory management with options for custom allocators and manual control.
78
79
```python { .api }
80
def new(self, cdecl, init=None): ...
81
def new_allocator(self, alloc=None, free=None, should_clear_after_alloc=True): ...
82
def cast(self, cdecl, source): ...
83
def addressof(self, cdata, *fields_or_indexes): ...
84
def gc(self, cdata, destructor, size=0): ...
85
```
86
87
[Memory Management](./memory-management.md)
88
89
### Type System
90
91
C type introspection and manipulation operations. The type system provides complete information about C types, sizes, alignment, and structure layouts.
92
93
```python { .api }
94
def typeof(self, cdecl): ...
95
def sizeof(self, cdecl): ...
96
def alignof(self, cdecl): ...
97
def offsetof(self, cdecl, *fields_or_indexes): ...
98
def getctype(self, cdecl, replace_with=''): ...
99
def list_types(self): ...
100
```
101
102
[Type System](./type-system.md)
103
104
### Data Conversion
105
106
Converting between Python and C data representations. These functions handle string conversion, array unpacking, buffer operations, and memory transfers.
107
108
```python { .api }
109
def string(self, cdata, maxlen=-1): ...
110
def unpack(self, cdata, length): ...
111
def from_buffer(self, cdecl, python_buffer, require_writable=False): ...
112
def memmove(self, dest, src, n): ...
113
buffer: callable # Buffer property for raw data access
114
```
115
116
[Data Conversion](./data-conversion.md)
117
118
### Callbacks and Handles
119
120
Creating Python callbacks for C code and managing Python object handles in C. Essential for bidirectional communication between Python and C.
121
122
```python { .api }
123
def callback(self, cdecl, python_callable=None, error=None, onerror=None): ...
124
def new_handle(self, x): ...
125
def from_handle(self, x): ...
126
def release(self, x): ...
127
```
128
129
[Callbacks and Handles](./callbacks-handles.md)
130
131
### Source Generation and Compilation
132
133
Advanced features for generating and compiling C extensions at runtime. These capabilities enable complex integration scenarios and performance optimization.
134
135
```python { .api }
136
def set_source(self, module_name, source, source_extension='.c', **kwds): ...
137
def set_source_pkgconfig(self, module_name, pkgconfig_libs, source, source_extension='.c', **kwds): ...
138
def compile(self, tmpdir='.', verbose=0, target=None, debug=None): ...
139
def emit_c_code(self, filename): ...
140
def emit_python_code(self, filename): ...
141
def distutils_extension(self, tmpdir='build', verbose=True): ...
142
```
143
144
[Source Generation](./source-generation.md)
145
146
### Error Handling and Utilities
147
148
Error management, system integration utilities, and platform-specific functionality including errno handling and Windows Unicode support.
149
150
```python { .api }
151
# Error handling
152
errno: property # C errno access
153
def getwinerror(self, code=-1): ...
154
155
# Utilities
156
def include(self, ffi_to_include): ...
157
def set_unicode(self, enabled_flag): ...
158
def init_once(self, func, tag): ...
159
def embedding_api(self, csource, packed=False, pack=None): ...
160
def embedding_init_code(self, pysource): ...
161
def def_extern(self, *args, **kwds): ...
162
```
163
164
[Error Handling](./error-handling.md)
165
166
## Exception Classes
167
168
```python { .api }
169
class FFIError(Exception): ...
170
class CDefError(Exception): ...
171
class VerificationError(Exception): ...
172
class VerificationMissing(Exception): ...
173
class PkgConfigError(Exception): ...
174
```
175
176
## Constants and Attributes
177
178
```python { .api }
179
# Version information
180
__version__: str # "1.17.1"
181
__version_info__: tuple # (1, 17, 1)
182
183
# FFI instance attributes
184
NULL: CData # NULL pointer constant
185
CData: type # Base class for C data objects
186
CType: type # Base class for C type objects
187
```
188
189
## Common Patterns
190
191
### Loading System Libraries
192
193
```python
194
ffi = FFI()
195
ffi.cdef("int puts(const char *s);")
196
libc = ffi.dlopen(None) # System C library
197
libc.puts(b"Hello from C!")
198
```
199
200
### Working with Structures
201
202
```python
203
ffi = FFI()
204
ffi.cdef("""
205
struct point {
206
int x, y;
207
};
208
""")
209
210
# Create and use struct
211
p = ffi.new("struct point *")
212
p.x = 10
213
p.y = 20
214
print(f"Point: ({p.x}, {p.y})")
215
```
216
217
### Memory Management with Arrays
218
219
```python
220
ffi = FFI()
221
222
# Allocate array
223
arr = ffi.new("int[]", [1, 2, 3, 4, 5])
224
print(len(arr)) # 5
225
print(arr[2]) # 3
226
227
# Convert to Python list
228
py_list = ffi.unpack(arr, len(arr))
229
print(py_list) # [1, 2, 3, 4, 5]
230
```