Debian Codegraph @

doc/source/using.rst

raw
1 ================================
2 Using the ffi/lib objects
3 ================================
4
5 .. contents::
6
7 Keep this page under your pillow.
8
9
10 .. _working:
11
12 Working with pointers, structures and arrays
13 --------------------------------------------
14
15 The C code's integers and floating-point values are mapped to Python's
16 regular ``int``, ``long`` and ``float``. Moreover, the C type ``char``
17 corresponds to single-character strings in Python. (If you want it to
18 map to small integers, use either ``signed char`` or ``unsigned char``.)
19
20 Similarly, the C type ``wchar_t`` corresponds to single-character
21 unicode strings. Note that in some situations (a narrow Python build
22 with an underlying 4-bytes wchar_t type), a single wchar_t character
23 may correspond to a pair of surrogates, which is represented as a
24 unicode string of length 2. If you need to convert such a 2-chars
25 unicode string to an integer, ``ord(x)`` does not work; use instead
26 ``int(ffi.cast('wchar_t', x))``.
27
28 *New in version 1.11:* in addition to ``wchar_t``, the C types
29 ``char16_t`` and ``char32_t`` work the same but with a known fixed size.
30 In previous versions, this could be achieved using ``uint16_t`` and
31 ``int32_t`` but without automatic conversion to Python unicodes.
32
33 Pointers, structures and arrays are more complex: they don't have an
34 obvious Python equivalent. Thus, they correspond to objects of type
35 ``cdata``, which are printed for example as
36 ``<cdata 'struct foo_s *' 0xa3290d8>``.
37
38 ``ffi.new(ctype, [initializer])``: this function builds and returns a
39 new cdata object of the given ``ctype``. The ctype is usually some
40 constant string describing the C type. It must be a pointer or array
41 type. If it is a pointer, e.g. ``"int *"`` or ``struct foo *``, then
42 it allocates the memory for one ``int`` or ``struct foo``. If it is
43 an array, e.g. ``int[10]``, then it allocates the memory for ten
44 ``int``. In both cases the returned cdata is of type ``ctype``.
45
46 The memory is initially filled with zeros. An initializer can be given
47 too, as described later.
48
49 Example::
50
51 >>> ffi.new("int *")
52 <cdata 'int *' owning 4 bytes>
53 >>> ffi.new("int[10]")
54 <cdata 'int[10]' owning 40 bytes>
55
56 >>> ffi.new("char *") # allocates only one char---not a C string!
57 <cdata 'char *' owning 1 bytes>
58 >>> ffi.new("char[]", "foobar") # this allocates a C string, ending in \0
59 <cdata 'char[]' owning 7 bytes>
60
61 Unlike C, the returned pointer object has *ownership* on the allocated
62 memory: when this exact object is garbage-collected, then the memory is
63 freed. If, at the level of C, you store a pointer to the memory
64 somewhere else, then make sure you also keep the object alive for as
65 long as needed. (This also applies if you immediately cast the returned
66 pointer to a pointer of a different type: only the original object has
67 ownership, so you must keep it alive. As soon as you forget it, then
68 the casted pointer will point to garbage! In other words, the ownership
69 rules are attached to the *wrapper* cdata objects: they are not, and
70 cannot, be attached to the underlying raw memory.) Example:
71
72 .. code-block:: python
73
74 global_weakkeydict = weakref.WeakKeyDictionary()
75
76 def make_foo():
77 s1 = ffi.new("struct foo *")
78 fld1 = ffi.new("struct bar *")
79 fld2 = ffi.new("struct bar *")
80 s1.thefield1 = fld1
81 s1.thefield2 = fld2
82 # here the 'fld1' and 'fld2' object must not go away,
83 # otherwise 's1.thefield1/2' will point to garbage!
84 global_weakkeydict[s1] = (fld1, fld2)
85 # now 's1' keeps alive 'fld1' and 'fld2'. When 's1' goes
86 # away, then the weak dictionary entry will be removed.
87 return s1
88
89 Usually you don't need a weak dict: for example, to call a function with
90 a ``char * *`` argument that contains a pointer to a ``char *`` pointer,
91 it is enough to do this:
92
93 .. code-block:: python
94
95 p = ffi.new("char[]", "hello, world") # p is a 'char *'
96 q = ffi.new("char **", p) # q is a 'char **'
97 lib.myfunction(q)
98 # p is alive at least until here, so that's fine
99
100 However, this is always wrong (usage of freed memory):
101
102 .. code-block:: python
103
104 p = ffi.new("char **", ffi.new("char[]", "hello, world"))
105 # WRONG! as soon as p is built, the inner ffi.new() gets freed!
106
107 This is wrong too, for the same reason:
108
109 .. code-block:: python
110
111 p = ffi.new("struct my_stuff")
112 p.foo = ffi.new("char[]", "hello, world")
113 # WRONG! as soon as p.foo is set, the ffi.new() gets freed!
114
115
116 The cdata objects support mostly the same operations as in C: you can
117 read or write from pointers, arrays and structures. Dereferencing a
118 pointer is done usually in C with the syntax ``*p``, which is not valid
119 Python, so instead you have to use the alternative syntax ``p[0]``
120 (which is also valid C). Additionally, the ``p.x`` and ``p->x``
121 syntaxes in C both become ``p.x`` in Python.
122
123 We have ``ffi.NULL`` to use in the same places as the C ``NULL``.
124 Like the latter, it is actually defined to be ``ffi.cast("void *",
125 0)``. For example, reading a NULL pointer returns a ``<cdata 'type *'
126 NULL>``, which you can check for e.g. by comparing it with
127 ``ffi.NULL``.
128
129 There is no general equivalent to the ``&`` operator in C (because it
130 would not fit nicely in the model, and it does not seem to be needed
131 here). There is `ffi.addressof()`__, but only for some cases. You
132 cannot take the "address" of a number in Python, for example; similarly,
133 you cannot take the address of a CFFI pointer. If you have this kind
134 of C code::
135
136 int x, y;
137 fetch_size(&x, &y);
138
139 opaque_t *handle; // some opaque pointer
140 init_stuff(&handle); // initializes the variable 'handle'
141 more_stuff(handle); // pass the handle around to more functions
142
143 then you need to rewrite it like this, replacing the variables in C
144 with what is logically pointers to the variables:
145
146 .. code-block:: python
147
148 px = ffi.new("int *")
149 py = ffi.new("int *") arr = ffi.new("int[2]")
150 lib.fetch_size(px, py) -OR- lib.fetch_size(arr, arr + 1)
151 x = px[0] x = arr[0]
152 y = py[0] y = arr[1]
153
154 p_handle = ffi.new("opaque_t **")
155 lib.init_stuff(p_handle) # pass the pointer to the 'handle' pointer
156 handle = p_handle[0] # now we can read 'handle' out of 'p_handle'
157 lib.more_stuff(handle)
158
159 .. __: ref.html#ffi-addressof
160
161
162 Any operation that would in C return a pointer or array or struct type
163 gives you a fresh cdata object. Unlike the "original" one, these fresh
164 cdata objects don't have ownership: they are merely references to
165 existing memory.
166
167 As an exception to the above rule, dereferencing a pointer that owns a
168 *struct* or *union* object returns a cdata struct or union object
169 that "co-owns" the same memory. Thus in this case there are two
170 objects that can keep the same memory alive. This is done for cases where
171 you really want to have a struct object but don't have any convenient
172 place to keep alive the original pointer object (returned by
173 ``ffi.new()``).
174
175 Example:
176
177 .. code-block:: python
178
179 # void somefunction(int *);
180
181 x = ffi.new("int *") # allocate one int, and return a pointer to it
182 x[0] = 42 # fill it
183 lib.somefunction(x) # call the C function
184 print x[0] # read the possibly-changed value
185
186 The equivalent of C casts are provided with ``ffi.cast("type", value)``.
187 They should work in the same cases as they do in C. Additionally, this
188 is the only way to get cdata objects of integer or floating-point type::
189
190 >>> x = ffi.cast("int", 42)
191 >>> x
192 <cdata 'int' 42>
193 >>> int(x)
194 42
195
196 To cast a pointer to an int, cast it to ``intptr_t`` or ``uintptr_t``,
197 which are defined by C to be large enough integer types (example on 32
198 bits)::
199
200 >>> int(ffi.cast("intptr_t", pointer_cdata)) # signed
201 -1340782304
202 >>> int(ffi.cast("uintptr_t", pointer_cdata)) # unsigned
203 2954184992L
204
205 The initializer given as the optional second argument to ``ffi.new()``
206 can be mostly anything that you would use as an initializer for C code,
207 with lists or tuples instead of using the C syntax ``{ .., .., .. }``.
208 Example::
209
210 typedef struct { int x, y; } foo_t;
211
212 foo_t v = { 1, 2 }; // C syntax
213 v = ffi.new("foo_t *", [1, 2]) # CFFI equivalent
214
215 foo_t v = { .y=1, .x=2 }; // C99 syntax
216 v = ffi.new("foo_t *", {'y': 1, 'x': 2}) # CFFI equivalent
217
218 Like C, arrays of chars can also be initialized from a string, in
219 which case a terminating null character is appended implicitly::
220
221 >>> x = ffi.new("char[]", "hello")
222 >>> x
223 <cdata 'char[]' owning 6 bytes>
224 >>> len(x) # the actual size of the array
225 6
226 >>> x[5] # the last item in the array
227 '\x00'
228 >>> x[0] = 'H' # change the first item
229 >>> ffi.string(x) # interpret 'x' as a regular null-terminated string
230 'Hello'
231
232 Similarly, arrays of wchar_t or char16_t or char32_t can be initialized
233 from a unicode string,
234 and calling ``ffi.string()`` on the cdata object returns the current unicode
235 string stored in the source array (adding surrogates if necessary).
236 See the `Unicode character types`__ section for more details.
237
238 .. __: ref.html#unichar
239
240 Note that unlike Python lists or tuples, but like C, you *cannot* index in
241 a C array from the end using negative numbers.
242
243 More generally, the C array types can have their length unspecified in C
244 types, as long as their length can be derived from the initializer, like
245 in C::
246
247 int array[] = { 1, 2, 3, 4 }; // C syntax
248 array = ffi.new("int[]", [1, 2, 3, 4]) # CFFI equivalent
249
250 As an extension, the initializer can also be just a number, giving
251 the length (in case you just want zero-initialization)::
252
253 int array[1000]; // C syntax
254 array = ffi.new("int[1000]") # CFFI 1st equivalent
255 array = ffi.new("int[]", 1000) # CFFI 2nd equivalent
256
257 This is useful if the length is not actually a constant, to avoid things
258 like ``ffi.new("int[%d]" % x)``. Indeed, this is not recommended:
259 ``ffi`` normally caches the string ``"int[]"`` to not need to re-parse
260 it all the time.
261
262 The C99 variable-sized structures are supported too, as long as the
263 initializer says how long the array should be:
264
265 .. code-block:: python
266
267 # typedef struct { int x; int y[]; } foo_t;
268
269 p = ffi.new("foo_t *", [5, [6, 7, 8]]) # length 3
270 p = ffi.new("foo_t *", [5, 3]) # length 3 with 0 in the array
271 p = ffi.new("foo_t *", {'y': 3}) # length 3 with 0 everywhere
272
273 Finally, note that any Python object used as initializer can also be
274 used directly without ``ffi.new()`` in assignments to array items or
275 struct fields. In fact, ``p = ffi.new("T*", initializer)`` is
276 equivalent to ``p = ffi.new("T*"); p[0] = initializer``. Examples:
277
278 .. code-block:: python
279
280 # if 'p' is a <cdata 'int[5][5]'>
281 p[2] = [10, 20] # writes to p[2][0] and p[2][1]
282
283 # if 'p' is a <cdata 'foo_t *'>, and foo_t has fields x, y and z
284 p[0] = {'x': 10, 'z': 20} # writes to p.x and p.z; p.y unmodified
285
286 # if, on the other hand, foo_t has a field 'char a[5]':
287 p.a = "abc" # writes 'a', 'b', 'c' and '\0'; p.a[4] unmodified
288
289 In function calls, when passing arguments, these rules can be used too;
290 see `Function calls`_.
291
292
293 Python 3 support
294 ----------------
295
296 Python 3 is supported, but the main point to note is that the ``char`` C
297 type corresponds to the ``bytes`` Python type, and not ``str``. It is
298 your responsibility to encode/decode all Python strings to bytes when
299 passing them to or receiving them from CFFI.
300
301 This only concerns the ``char`` type and derivative types; other parts
302 of the API that accept strings in Python 2 continue to accept strings in
303 Python 3.
304
305
306 An example of calling a main-like thing
307 ---------------------------------------
308
309 Imagine we have something like this:
310
311 .. code-block:: python
312
313 from cffi import FFI
314 ffi = FFI()
315 ffi.cdef("""
316 int main_like(int argv, char *argv[]);
317 """)
318 lib = ffi.dlopen("some_library.so")
319
320 Now, everything is simple, except, how do we create the ``char**`` argument
321 here?
322 The first idea:
323
324 .. code-block:: python
325
326 lib.main_like(2, ["arg0", "arg1"])
327
328 does not work, because the initializer receives two Python ``str`` objects
329 where it was expecting ``<cdata 'char *'>`` objects. You need to use
330 ``ffi.new()`` explicitly to make these objects:
331
332 .. code-block:: python
333
334 lib.main_like(2, [ffi.new("char[]", "arg0"),
335 ffi.new("char[]", "arg1")])
336
337 Note that the two ``<cdata 'char[]'>`` objects are kept alive for the
338 duration of the call: they are only freed when the list itself is freed,
339 and the list is only freed when the call returns.
340
341 If you want instead to build an "argv" variable that you want to reuse,
342 then more care is needed:
343
344 .. code-block:: python
345
346 # DOES NOT WORK!
347 argv = ffi.new("char *[]", [ffi.new("char[]", "arg0"),
348 ffi.new("char[]", "arg1")])
349
350 In the above example, the inner "arg0" string is deallocated as soon
351 as "argv" is built. You have to make sure that you keep a reference
352 to the inner "char[]" objects, either directly or by keeping the list
353 alive like this:
354
355 .. code-block:: python
356
357 argv_keepalive = [ffi.new("char[]", "arg0"),
358 ffi.new("char[]", "arg1")]
359 argv = ffi.new("char *[]", argv_keepalive)
360
361
362 Function calls
363 --------------
364
365 When calling C functions, passing arguments follows mostly the same
366 rules as assigning to structure fields, and the return value follows the
367 same rules as reading a structure field. For example:
368
369 .. code-block:: python
370
371 # int foo(short a, int b);
372
373 n = lib.foo(2, 3) # returns a normal integer
374 lib.foo(40000, 3) # raises OverflowError
375
376 You can pass to ``char *`` arguments a normal Python string (but don't
377 pass a normal Python string to functions that take a ``char *``
378 argument and may mutate it!):
379
380 .. code-block:: python
381
382 # size_t strlen(const char *);
383
384 assert lib.strlen("hello") == 5
385
386 (Note that there is no guarantee that the ``char *`` passed to the
387 function remains valid after the call is done. Similarly, if you write
388 ``lib.f(x); lib.f(x)`` where ``x`` is a variable containing a byte string,
389 the two calls to ``f()`` could sometimes receive different ``char *``
390 pointers, with each of them only valid during the corresponding call. This is
391 important notably for PyPy which uses many optimizations tweaking the data
392 underlying a byte string object. CFFI will not make and free a copy of
393 the whole string at *every* call---it usually won't---but you *cannot*
394 write code that relies on it: there are cases where that would break.
395 If you need a pointer to remain valid, you need to make one explicitly,
396 for example with ``ptr = ffi.new("char[]", x)``.)
397
398 You can also pass unicode strings as ``wchar_t *`` or ``char16_t *`` or
399 ``char32_t *`` arguments. Note that
400 the C language makes no difference between argument declarations that
401 use ``type *`` or ``type[]``. For example, ``int *`` is fully
402 equivalent to ``int[]`` (or even ``int[5]``; the 5 is ignored). For CFFI,
403 this means that you can always pass arguments that can be converted to
404 either ``int *`` or ``int[]``. For example:
405
406 .. code-block:: python
407
408 # void do_something_with_array(int *array);
409
410 lib.do_something_with_array([1, 2, 3, 4, 5]) # works for int[]
411
412 See `Reference: conversions`__ for a similar way to pass ``struct foo_s
413 *`` arguments---but in general, it is clearer in this case to pass
414 ``ffi.new('struct foo_s *', initializer)``.
415
416 __ ref.html#conversions
417
418 CFFI supports passing and returning structs and unions to functions and
419 callbacks. Example:
420
421 .. code-block:: python
422
423 # struct foo_s { int a, b; };
424 # struct foo_s function_returning_a_struct(void);
425
426 myfoo = lib.function_returning_a_struct()
427 # `myfoo`: <cdata 'struct foo_s' owning 8 bytes>
428
429 For performance, non-variadic API-level functions that you get by
430 writing ``lib.some_function`` are not ``<cdata>``
431 objects, but an object of a different type (on CPython, ``<built-in
432 function>``). This means you cannot pass them directly to some other C
433 function expecting a function pointer argument. Only ``ffi.typeof()``
434 works on them. To get a cdata containing a regular function pointer,
435 use ``ffi.addressof(lib, "name")``.
436
437 There are a few (obscure) limitations to the supported argument and
438 return types. These limitations come from libffi and apply only to
439 calling ``<cdata>`` function pointers; in other words, they don't
440 apply to non-variadic ``cdef()``-declared functions if you are using
441 the API mode. The limitations are that you cannot pass directly as
442 argument or return type:
443
444 * a union (but a *pointer* to a union is fine);
445
446 * a struct which uses bitfields (but a *pointer* to such a struct is
447 fine);
448
449 * a struct that was declared with "``...``" in the ``cdef()``.
450
451 In API mode, you can work around these limitations: for example, if you
452 need to call such a function pointer from Python, you can instead write
453 a custom C function that accepts the function pointer and the real
454 arguments and that does the call from C. Then declare that custom C
455 function in the ``cdef()`` and use it from Python.
456
457
458 Variadic function calls
459 -----------------------
460
461 Variadic functions in C (which end with "``...``" as their last
462 argument) can be declared and called normally, with the exception that
463 all the arguments passed in the variable part *must* be cdata objects.
464 This is because it would not be possible to guess, if you wrote this::
465
466 lib.printf("hello, %d\n", 42) # doesn't work!
467
468 that you really meant the 42 to be passed as a C ``int``, and not a
469 ``long`` or ``long long``. The same issue occurs with ``float`` versus
470 ``double``. So you have to force cdata objects of the C type you want,
471 if necessary with ``ffi.cast()``:
472
473 .. code-block:: python
474
475 lib.printf("hello, %d\n", ffi.cast("int", 42))
476 lib.printf("hello, %ld\n", ffi.cast("long", 42))
477 lib.printf("hello, %f\n", ffi.cast("double", 42))
478
479 But of course:
480
481 .. code-block:: python
482
483 lib.printf("hello, %s\n", ffi.new("char[]", "world"))
484
485 Note that if you are using ``dlopen()``, the function declaration in the
486 ``cdef()`` must match the original one in C exactly, as usual --- in
487 particular, if this function is variadic in C, then its ``cdef()``
488 declaration must also be variadic. You cannot declare it in the
489 ``cdef()`` with fixed arguments instead, even if you plan to only call
490 it with these argument types. The reason is that some architectures
491 have a different calling convention depending on whether the function
492 signature is fixed or not. (On x86-64, the difference can sometimes be
493 seen in PyPy's JIT-generated code if some arguments are ``double``.)
494
495 Note that the function signature ``int foo();`` is interpreted by CFFI
496 as equivalent to ``int foo(void);``. This differs from the C standard,
497 in which ``int foo();`` is really like ``int foo(...);`` and can be
498 called with any arguments. (This feature of C is a pre-C89 relic: the
499 arguments cannot be accessed at all in the body of ``foo()`` without
500 relying on compiler-specific extensions. Nowadays virtually all code
501 with ``int foo();`` really means ``int foo(void);``.)
502
503
504 Memory pressure (PyPy)
505 ----------------------
506
507 This paragraph applies only to PyPy, because its garbage collector (GC)
508 is different from CPython's. It is very common in C code to have pairs
509 of functions, one which performs memory allocations or acquires other
510 resources, and the other which frees them again. Depending on how you
511 structure your Python code, the freeing function is only called when the
512 GC decides a particular (Python) object can be freed. This occurs
513 notably in these cases:
514
515 * If you use a ``__del__()`` method to call the freeing function.
516
517 * If you use ``ffi.gc()`` without also using ``ffi.release()``.
518
519 * This does not occur if you call the freeing function at a
520 deterministic time, like in a regular ``try: finally:`` block. It
521 does however occur *inside a generator---* if the generator is not
522 explicitly exhausted but forgotten at a ``yield`` point, then the code
523 in the enclosing ``finally`` block is only invoked at the next GC.
524
525 In these cases, you may have to use the built-in function
526 ``__pypy__.add_memory_pressure(n)``. Its argument ``n`` is an estimate
527 of how much memory pressure to add. For example, if the pair of C
528 functions that we are talking about is ``malloc(n)`` and ``free()`` or
529 similar, you would call ``__pypy__.add_memory_pressure(n)`` after
530 ``malloc(n)``. Doing so is not always a complete answer to the problem,
531 but it makes the next GC occur earlier, which is often enough.
532
533 The same applies if the memory allocations are indirect, e.g. the C
534 function allocates some internal data structures. In that case, call
535 ``__pypy__.add_memory_pressure(n)`` with an argument ``n`` that is a
536 rough estimation. Knowing the exact size is not important, and memory
537 pressure doesn't have to be manually brought down again after calling
538 the freeing function. If you are writing wrappers for the allocating /
539 freeing pair of functions, you should probably call
540 ``__pypy__.add_memory_pressure()`` in the former even if the user may
541 invoke the latter at a known point with a ``finally:`` block.
542
543 In case this solution is not sufficient, or if the acquired resource is
544 not memory but something else more limited (like file descriptors), then
545 there is no better way than restructuring your code to make sure the
546 freeing function is called at a known point and not indirectly by the
547 GC.
548
549 Note that in PyPy <= 5.6 the discussion above also applies to
550 ``ffi.new()``. In more recent versions of PyPy, both ``ffi.new()`` and
551 ``ffi.new_allocator()()`` automatically account for the memory pressure
552 they create. (In case you need to support both older and newer PyPy's,
553 try calling ``__pypy__.add_memory_pressure()`` anyway; it is better to
554 overestimate than not account for the memory pressure.)
555
556
557 .. _extern-python:
558 .. _`extern "Python"`:
559
560 Extern "Python" (new-style callbacks)
561 -------------------------------------
562
563 When the C code needs a pointer to a function which invokes back a
564 Python function of your choice, here is how you do it in the
565 out-of-line API mode. The next section about Callbacks_ describes the
566 ABI-mode solution.
567
568 This is *new in version 1.4.* Use old-style Callbacks_ if backward
569 compatibility is an issue. (The original callbacks are slower to
570 invoke and have the same issue as libffi's callbacks; notably, see the
571 warning__. The new style described in the present section does not
572 use libffi's callbacks at all.)
573
574 .. __: Callbacks_
575
576 In the builder script, declare in the cdef a function prefixed with
577 ``extern "Python"``::
578
579 ffibuilder.cdef("""
580 extern "Python" int my_callback(int, int);
581
582 void library_function(int(*callback)(int, int));
583 """)
584 ffibuilder.set_source("_my_example", r"""
585 #include <some_library.h>
586 """)
587
588 The function ``my_callback()`` is then implemented in Python inside
589 your application's code::
590
591 from _my_example import ffi, lib
592
593 @ffi.def_extern()
594 def my_callback(x, y):
595 return 42
596
597 You obtain a ``<cdata>`` pointer-to-function object by getting
598 ``lib.my_callback``. This ``<cdata>`` can be passed to C code and
599 then works like a callback: when the C code calls this function
600 pointer, the Python function ``my_callback`` is called. (You need
601 to pass ``lib.my_callback`` to C code, and not ``my_callback``: the
602 latter is just the Python function above, which cannot be passed to C.)
603
604 CFFI implements this by defining ``my_callback`` as a static C
605 function, written after the ``set_source()`` code. The ``<cdata>``
606 then points to this function. What this function does is invoke the
607 Python function object that is, at runtime, attached with
608 ``@ffi.def_extern()``.
609
610 The ``@ffi.def_extern()`` decorator should be applied to **global
611 functions,** one for each ``extern "Python"`` function of the same
612 name.
613
614 To support some corner cases, it is possible to redefine the attached
615 Python function by calling ``@ffi.def_extern()`` again for the same
616 name---but this is not recommended! Better attach a single global
617 Python function for this name, and write it more flexibly in the first
618 place. This is because each ``extern "Python"`` function turns into
619 only one C function. Calling ``@ffi.def_extern()`` again changes this
620 function's C logic to call the new Python function; the old Python
621 function is not callable any more. The C function pointer you get
622 from ``lib.my_function`` is always this C function's address, i.e. it
623 remains the same.
624
625 Extern "Python" and ``void *`` arguments
626 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
627
628 As described just before, you cannot use ``extern "Python"`` to make a
629 variable number of C function pointers. However, achieving that
630 result is not possible in pure C code either. For this reason, it is
631 usual for C to define callbacks with a ``void *data`` argument. You
632 can use ``ffi.new_handle()`` and ``ffi.from_handle()`` to pass a
633 Python object through this ``void *`` argument. For example, if the C
634 type of the callbacks is::
635
636 typedef void (*event_cb_t)(event_t *evt, void *userdata);
637
638 and you register events by calling this function::
639
640 void event_cb_register(event_cb_t cb, void *userdata);
641
642 Then you would write this in the build script::
643
644 ffibuilder.cdef("""
645 typedef ... event_t;
646 typedef void (*event_cb_t)(event_t *evt, void *userdata);
647 void event_cb_register(event_cb_t cb, void *userdata);
648
649 extern "Python" void my_event_callback(event_t *, void *);
650 """)
651 ffibuilder.set_source("_demo_cffi", r"""
652 #include <the_event_library.h>
653 """)
654
655 and in your main application you register events like this::
656
657 from _demo_cffi import ffi, lib
658
659 class Widget(object):
660 def __init__(self):
661 userdata = ffi.new_handle(self)
662 self._userdata = userdata # must keep this alive!
663 lib.event_cb_register(lib.my_event_callback, userdata)
664
665 def process_event(self, evt):
666 print "got event!"
667
668 @ffi.def_extern()
669 def my_event_callback(evt, userdata):
670 widget = ffi.from_handle(userdata)
671 widget.process_event(evt)
672
673 Some other libraries don't have an explicit ``void *`` argument, but
674 let you attach the ``void *`` to an existing structure. For example,
675 the library might say that ``widget->userdata`` is a generic field
676 reserved for the application. If the event's signature is now this::
677
678 typedef void (*event_cb_t)(widget_t *w, event_t *evt);
679
680 Then you can use the ``void *`` field in the low-level
681 ``widget_t *`` like this::
682
683 from _demo_cffi import ffi, lib
684
685 class Widget(object):
686 def __init__(self):
687 ll_widget = lib.new_widget(500, 500)
688 self.ll_widget = ll_widget # <cdata 'struct widget *'>
689 userdata = ffi.new_handle(self)
690 self._userdata = userdata # must still keep this alive!
691 ll_widget.userdata = userdata # this makes a copy of the "void *"
692 lib.event_cb_register(ll_widget, lib.my_event_callback)
693
694 def process_event(self, evt):
695 print "got event!"
696
697 @ffi.def_extern()
698 def my_event_callback(ll_widget, evt):
699 widget = ffi.from_handle(ll_widget.userdata)
700 widget.process_event(evt)
701
702 Extern "Python" accessed from C directly
703 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
704
705 In case you want to access some ``extern "Python"`` function directly
706 from the C code written in ``set_source()``, you need to write a
707 forward declaration. (By default it needs to be static, but see
708 `next paragraph`__.) The real implementation of this function
709 is added by CFFI *after* the C code---this is needed because the
710 declaration might use types defined by ``set_source()``
711 (e.g. ``event_t`` above, from the ``#include``), so it cannot be
712 generated before.
713
714 .. __: `extern-python-c`_
715
716 ::
717
718 ffibuilder.set_source("_demo_cffi", r"""
719 #include <the_event_library.h>
720
721 static void my_event_callback(widget_t *, event_t *);
722
723 /* here you can write C code which uses '&my_event_callback' */
724 """)
725
726 This can also be used to write custom C code which calls Python
727 directly. Here is an example (inefficient in this case, but might be
728 useful if the logic in ``my_algo()`` is much more complex)::
729
730 ffibuilder.cdef("""
731 extern "Python" int f(int);
732 int my_algo(int);
733 """)
734 ffibuilder.set_source("_example_cffi", r"""
735 static int f(int); /* the forward declaration */
736
737 static int my_algo(int n) {
738 int i, sum = 0;
739 for (i = 0; i < n; i++)
740 sum += f(i); /* call f() here */
741 return sum;
742 }
743 """)
744
745 .. _extern-python-c:
746
747 Extern "Python+C"
748 ~~~~~~~~~~~~~~~~~
749
750 Functions declared with ``extern "Python"`` are generated as
751 ``static`` functions in the C source. However, in some cases it is
752 convenient to make them non-static, typically when you want to make
753 them directly callable from other C source files. To do that, you can
754 say ``extern "Python+C"`` instead of just ``extern "Python"``. *New
755 in version 1.6.*
756
757 +------------------------------------+--------------------------------------+
758 | if the cdef contains | then CFFI generates |
759 +------------------------------------+--------------------------------------+
760 | ``extern "Python" int f(int);`` | ``static int f(int) { /* code */ }`` |
761 +------------------------------------+--------------------------------------+
762 | ``extern "Python+C" int f(int);`` | ``int f(int) { /* code */ }`` |
763 +------------------------------------+--------------------------------------+
764
765 The name ``extern "Python+C"`` comes from the fact that we want an
766 extern function in both senses: as an ``extern "Python"``, and as a
767 C function that is not static.
768
769 You cannot make CFFI generate additional macros or other
770 compiler-specific stuff like the GCC ``__attribute__``. You can only
771 control whether the function should be ``static`` or not. But often,
772 these attributes must be written alongside the function *header*, and
773 it is fine if the function *implementation* does not repeat them::
774
775 ffibuilder.cdef("""
776 extern "Python+C" int f(int); /* not static */
777 """)
778 ffibuilder.set_source("_example_cffi", r"""
779 /* the forward declaration, setting a gcc attribute
780 (this line could also be in some .h file, to be included
781 both here and in the other C files of the project) */
782 int f(int) __attribute__((visibility("hidden")));
783 """)
784
785
786 Extern "Python": reference
787 ~~~~~~~~~~~~~~~~~~~~~~~~~~
788
789 ``extern "Python"`` must appear in the cdef(). Like the C++ ``extern
790 "C"`` syntax, it can also be used with braces around a group of
791 functions::
792
793 extern "Python" {
794 int foo(int);
795 int bar(int);
796 }
797
798 The ``extern "Python"`` functions cannot be variadic for now. This
799 may be implemented in the future. (`This demo`__ shows how to do it
800 anyway, but it is a bit lengthy.)
801
802 .. __: https://github.com/python-cffi/cffi/blob/main/demo/extern_python_varargs.py
803
804 Each corresponding Python callback function is defined with the
805 ``@ffi.def_extern()`` decorator. Be careful when writing this
806 function: if it raises an exception, or tries to return an object of
807 the wrong type, then the exception cannot be propagated. Instead, the
808 exception is printed to stderr and the C-level callback is made to
809 return a default value. This can be controlled with ``error`` and
810 ``onerror``, described below.
811
812 .. _def-extern:
813
814 The ``@ffi.def_extern()`` decorator takes these optional arguments:
815
816 * ``name``: the name of the function as written in the cdef. By default
817 it is taken from the name of the Python function you decorate.
818
819 .. _error_onerror:
820
821 * ``error``: the returned value in case the Python function raises an
822 exception. It is 0 or null by default. The exception is still
823 printed to stderr, so this should be used only as a last-resort
824 solution.
825
826 * ``onerror``: if you want to be sure to catch all exceptions, use
827 ``@ffi.def_extern(onerror=my_handler)``. If an exception occurs and
828 ``onerror`` is specified, then ``onerror(exception, exc_value,
829 traceback)`` is called. This is useful in some situations where you
830 cannot simply write ``try: except:`` in the main callback function,
831 because it might not catch exceptions raised by signal handlers: if
832 a signal occurs while in C, the Python signal handler is called as
833 soon as possible, which is after entering the callback function but
834 *before* executing even the ``try:``. If the signal handler raises,
835 we are not in the ``try: except:`` yet.
836
837 If ``onerror`` is called and returns normally, then it is assumed
838 that it handled the exception on its own and nothing is printed to
839 stderr. If ``onerror`` raises, then both tracebacks are printed.
840 Finally, ``onerror`` can itself provide the result value of the
841 callback in C, but doesn't have to: if it simply returns None---or
842 if ``onerror`` itself fails---then the value of ``error`` will be
843 used, if any.
844
845 Note the following hack: in ``onerror``, you can access the original
846 callback arguments as follows. First check if ``traceback`` is not
847 None (it is None e.g. if the whole function ran successfully but
848 there was an error converting the value returned: this occurs after
849 the call). If ``traceback`` is not None, then
850 ``traceback.tb_frame`` is the frame of the outermost function,
851 i.e. directly the frame of the function decorated with
852 ``@ffi.def_extern()``. So you can get the value of ``argname`` in
853 that frame by reading ``traceback.tb_frame.f_locals['argname']``.
854
855
856 .. _Callbacks:
857
858 Callbacks (old style)
859 ---------------------
860
861 Here is how to make a new ``<cdata>`` object that contains a pointer
862 to a function, where that function invokes back a Python function of
863 your choice::
864
865 >>> @ffi.callback("int(int, int)")
866 >>> def myfunc(x, y):
867 ... return x + y
868 ...
869 >>> myfunc
870 <cdata 'int(*)(int, int)' calling <function myfunc at 0xf757bbc4>>
871
872 Note that ``"int(*)(int, int)"`` is a C *function pointer* type, whereas
873 ``"int(int, int)"`` is a C *function* type. Either can be specified to
874 ffi.callback() and the result is the same.
875
876 .. warning::
877
878 Callbacks are provided for the ABI mode or for backward
879 compatibility. If you are using the out-of-line API mode, it is
880 recommended to use the `extern "Python"`_ mechanism instead of
881 callbacks: it gives faster and cleaner code. It also avoids several
882 issues with old-style callbacks:
883
884 - On less common architecture, libffi is more likely to crash on
885 callbacks (`e.g. on NetBSD`__);
886
887 - On hardened systems like PAX and SELinux, the extra memory
888 protections can interfere (for example, on SELinux you need to
889 run with ``deny_execmem`` set to ``off``).
890
891 - `On Mac OS X,`__ you need to give your application the entitlement
892 ``com.apple.security.cs.allow-unsigned-executable-memory``.
893
894 - On Linux, ``systemd`` installs syscall filtering rules on services
895 it supervises. The `MemoryDenyWriteExecute=` setting in
896 `systemd.exec(5)` defaults to on, and can quietly block this.
897
898 Note also that a cffi fix for this issue was attempted---see
899 the ``ffi_closure_alloc`` branch---but was not merged because it
900 creates potential `memory corruption`__ with ``fork()``.
901
902 In other words: yes, it is dangerous to allow write+execute memory in your
903 program; that's why the various "hardening" options above exist. But at
904 the same time, these options open wide the door to another attack: if the
905 program forks and then attempts to call any of the ``ffi.callback()``, then
906 this immediately results in a crash---or, with a minimal amount of work
907 from an attacker, arbitrary code execution. To me it sounds even more
908 dangerous than the original problem, and that's why cffi is not playing
909 along.
910
911 To fix the issue once and for all on the affected platforms, you need
912 to refactor the involved code so that it no longer uses ``ffi.callback()``.
913
914 .. __: https://github.com/pyca/pyopenssl/issues/596
915 .. __: https://foss.heptapod.net/pypy/cffi/-/issues/391
916 .. __: https://bugzilla.redhat.com/show_bug.cgi?id=1249685
917
918 Warning: like ffi.new(), ffi.callback() returns a cdata that has
919 ownership of its C data. (In this case, the necessary C data contains
920 the libffi data structures to do a callback.) This means that the
921 callback can only be invoked as long as this cdata object is alive.
922 If you store the function pointer into C code, then make sure you also
923 keep this object alive for as long as the callback may be invoked.
924 The easiest way to do that is to always use ``@ffi.callback()`` at
925 module-level only, and to pass "context" information around with
926 `ffi.new_handle()`__, if possible. Example:
927
928 .. __: ref.html#new-handle
929
930 .. code-block:: python
931
932 # a good way to use this decorator is once at global level
933 @ffi.callback("int(int, void *)")
934 def my_global_callback(x, handle):
935 return ffi.from_handle(handle).some_method(x)
936
937
938 class Foo(object):
939
940 def __init__(self):
941 handle = ffi.new_handle(self)
942 self._handle = handle # must be kept alive
943 lib.register_stuff_with_callback_and_voidp_arg(my_global_callback, handle)
944
945 def some_method(self, x):
946 print "method called!"
947
948 (See also the section about `extern "Python"`_ above, where the same
949 general style is used.)
950
951 Note that callbacks of a variadic function type are not supported. A
952 workaround is to add custom C code. In the following example, a
953 callback gets a first argument that counts how many extra ``int``
954 arguments are passed:
955
956 .. code-block:: python
957
958 # file "example_build.py"
959
960 import cffi
961
962 ffibuilder = cffi.FFI()
963 ffibuilder.cdef("""
964 int (*python_callback)(int how_many, int *values);
965 void *const c_callback; /* pass this const ptr to C routines */
966 """)
967 ffibuilder.set_source("_example", r"""
968 #include <stdarg.h>
969 #include <alloca.h>
970 static int (*python_callback)(int how_many, int *values);
971 static int c_callback(int how_many, ...) {
972 va_list ap;
973 /* collect the "..." arguments into the values[] array */
974 int i, *values = alloca(how_many * sizeof(int));
975 va_start(ap, how_many);
976 for (i=0; i<how_many; i++)
977 values[i] = va_arg(ap, int);
978 va_end(ap);
979 return python_callback(how_many, values);
980 }
981 """)
982 ffibuilder.compile(verbose=True)
983
984 .. code-block:: python
985
986 # file "example.py"
987
988 from _example import ffi, lib
989
990 @ffi.callback("int(int, int *)")
991 def python_callback(how_many, values):
992 print ffi.unpack(values, how_many)
993 return 0
994 lib.python_callback = python_callback
995
996 Deprecated: you can also use ``ffi.callback()`` not as a decorator but
997 directly as ``ffi.callback("int(int, int)", myfunc)``. This is
998 discouraged: using this a style, we are more likely to forget the
999 callback object too early, when it is still in use.
1000
1001 The ``ffi.callback()`` decorator also accepts the optional argument
1002 ``error``, and from CFFI version 1.2 the optional argument ``onerror``.
1003 These two work in the same way as `described above for extern "Python".`__
1004
1005 .. __: error_onerror_
1006
1007
1008
1009 Windows: calling conventions
1010 ----------------------------
1011
1012 On Win32, functions can have two main calling conventions: either
1013 "cdecl" (the default), or "stdcall" (also known as "WINAPI"). There
1014 are also other rare calling conventions, but these are not supported.
1015 *New in version 1.3.*
1016
1017 When you issue calls from Python to C, the implementation is such that
1018 it works with any of these two main calling conventions; you don't
1019 have to specify it. However, if you manipulate variables of type
1020 "function pointer" or declare callbacks, then the calling convention
1021 must be correct. This is done by writing ``__cdecl`` or ``__stdcall``
1022 in the type, like in C::
1023
1024 @ffi.callback("int __stdcall(int, int)")
1025 def AddNumbers(x, y):
1026 return x + y
1027
1028 or::
1029
1030 ffibuilder.cdef("""
1031 struct foo_s {
1032 int (__stdcall *MyFuncPtr)(int, int);
1033 };
1034 """)
1035
1036 ``__cdecl`` is supported but is always the default so it can be left
1037 out. In the ``cdef()``, you can also use ``WINAPI`` as equivalent to
1038 ``__stdcall``. As mentioned above, it is mostly not needed (but doesn't
1039 hurt) to say ``WINAPI`` or ``__stdcall`` when declaring a plain
1040 function in the ``cdef()``. (The difference can still be seen if you
1041 take explicitly a pointer to this function with ``ffi.addressof()``,
1042 or if the function is ``extern "Python"``.)
1043
1044 These calling convention specifiers are accepted but ignored on any
1045 platform other than 32-bit Windows.
1046
1047 In CFFI versions before 1.3, the calling convention specifiers are not
1048 recognized. In API mode, you could work around it by using an
1049 indirection, like in the example in the section about Callbacks_
1050 (``"example_build.py"``). There was no way to use stdcall callbacks
1051 in ABI mode.
1052
1053
1054 FFI Interface
1055 -------------
1056
1057 (The reference for the FFI interface has been moved to the `next page`__.)
1058
1059 .. __: ref.html