0
# Core FFI Operations
1
2
Fundamental FFI functionality including instance creation, C code declaration parsing, and dynamic library loading. These operations form the foundation of all CFFI usage patterns.
3
4
## Capabilities
5
6
### FFI Instance Creation
7
8
Creates a new FFI instance that manages C declarations, type system, and backend operations.
9
10
```python { .api }
11
class FFI:
12
def __init__(self, backend=None):
13
"""
14
Create an FFI instance.
15
16
Parameters:
17
- backend: Optional backend override (mostly for testing)
18
19
Returns:
20
FFI instance with initialized parser and type system
21
"""
22
```
23
24
### C Declaration Parsing
25
26
Parses C source code declarations and registers functions, types, and global variables for later use.
27
28
```python { .api }
29
def cdef(self, csource, override=False, packed=False, pack=None):
30
"""
31
Parse the given C source declarations.
32
33
Parameters:
34
- csource (str): C source code containing declarations
35
- override (bool): Allow overriding existing declarations
36
- packed (bool): Pack all structs without field alignment
37
- pack (int): Maximum alignment for struct fields
38
39
Returns:
40
None (modifies FFI instance state)
41
"""
42
```
43
44
**Usage Example:**
45
46
```python
47
ffi = FFI()
48
ffi.cdef("""
49
// Function declarations
50
int printf(const char *format, ...);
51
void *malloc(size_t size);
52
void free(void *ptr);
53
54
// Structure definitions
55
struct point {
56
int x, y;
57
};
58
59
// Type definitions
60
typedef struct point point_t;
61
62
// Constants and enums
63
enum color { RED, GREEN, BLUE };
64
65
// Global variables
66
extern int errno;
67
""")
68
```
69
70
### Dynamic Library Loading
71
72
Loads dynamic libraries and makes their symbols available through the declared C interface.
73
74
```python { .api }
75
def dlopen(self, name, flags=0):
76
"""
77
Load and return a dynamic library.
78
79
Parameters:
80
- name (str|None): Library name/path, or None for standard C library
81
- flags (int): Loading flags (platform-specific)
82
83
Returns:
84
Library object with access to declared functions and variables
85
"""
86
```
87
88
**Usage Examples:**
89
90
```python
91
# Load standard C library
92
libc = ffi.dlopen(None)
93
libc.printf(b"Hello, World!\n")
94
95
# Load specific library
96
libm = ffi.dlopen("libm.so.6") # Linux
97
# libm = ffi.dlopen("msvcrt.dll") # Windows
98
99
# Access library functions
100
result = libm.sin(3.14159 / 2)
101
```
102
103
### Library Closing
104
105
Closes a previously opened dynamic library and invalidates access to its symbols.
106
107
```python { .api }
108
def dlclose(self, lib):
109
"""
110
Close a library obtained with ffi.dlopen().
111
112
Parameters:
113
- lib: Library object returned by dlopen()
114
115
Returns:
116
None
117
118
Warning: Access to functions/variables after closing may cause segfaults
119
"""
120
```
121
122
### Code Verification and Compilation
123
124
Verifies that C declarations compile correctly and returns a compiled library object with C-level API compatibility.
125
126
```python { .api }
127
def verify(self, source='', tmpdir=None, **kwargs):
128
"""
129
Verify declarations compile and return dynamic library.
130
131
Parameters:
132
- source (str): Additional C source code for compilation
133
- tmpdir (str): Temporary directory for compilation files
134
- **kwargs: Additional compilation options
135
136
Returns:
137
Compiled library object with declared interface
138
"""
139
```
140
141
**Usage Example:**
142
143
```python
144
ffi = FFI()
145
ffi.cdef("""
146
int add(int a, int b);
147
""")
148
149
lib = ffi.verify("""
150
int add(int a, int b) {
151
return a + b;
152
}
153
""")
154
155
result = lib.add(5, 3) # Returns 8
156
```
157
158
### Embedding API Declaration
159
160
Declares functions for embedding Python in C applications.
161
162
```python { .api }
163
def embedding_api(self, csource, packed=False, pack=None):
164
"""
165
Declare embedding API for Python-in-C integration.
166
167
Parameters:
168
- csource (str): C source code with function declarations
169
- packed (bool): Pack structs without alignment
170
- pack (int): Maximum struct alignment
171
172
Returns:
173
None (enables embedding mode)
174
"""
175
```
176
177
## Error Conditions
178
179
- **CDefError**: Raised for invalid C syntax or declarations
180
- **OSError**: Raised when library loading fails
181
- **VerificationError**: Raised when verification/compilation fails
182
- **TypeError**: Raised for invalid parameter types
183
184
## Integration Patterns
185
186
### Multiple Library Loading
187
188
```python
189
ffi = FFI()
190
ffi.cdef("""
191
// Math functions
192
double sin(double x);
193
double cos(double x);
194
195
// String functions
196
char *strcpy(char *dest, const char *src);
197
int strcmp(const char *s1, const char *s2);
198
""")
199
200
# Load multiple libraries
201
libm = ffi.dlopen("libm.so.6")
202
libc = ffi.dlopen(None)
203
204
# Use functions from different libraries
205
angle = libm.sin(3.14159 / 4)
206
libc.printf(b"sin(π/4) = %f\n", angle)
207
```
208
209
### Declaration Override
210
211
```python
212
ffi = FFI()
213
ffi.cdef("int func(int x);")
214
215
# Later override with more specific declaration
216
ffi.cdef("int func(int x, int y);", override=True)
217
```
218
219
### Packed Structures
220
221
```python
222
ffi = FFI()
223
ffi.cdef("""
224
struct packed_data {
225
char flag;
226
int value;
227
char data[100];
228
};
229
""", packed=True)
230
231
# Structure fields are tightly packed without padding
232
```