Debian Codegraph @

doc/source/ref.rst

raw
1 ================================
2 CFFI Reference
3 ================================
4
5 .. contents::
6
7
8 FFI Interface
9 -------------
10
11 *This page documents the runtime interface of the two types "FFI" and
12 "CompiledFFI". These two types are very similar to each other. You get
13 a CompiledFFI object if you import an out-of-line module. You get a FFI
14 object from explicitly writing cffi.FFI(). Unlike CompiledFFI, the type
15 FFI has also got additional methods documented on the* `next page`__.
16
17 .. __: cdef.html
18
19
20 ffi.NULL
21 ++++++++
22
23 **ffi.NULL**: a constant NULL of type ``<cdata 'void *'>``.
24
25
26 ffi.error
27 +++++++++
28
29 **ffi.error**: the Python exception raised in various cases. (Don't
30 confuse it with ``ffi.errno``.)
31
32
33 .. _new:
34
35 ffi.new()
36 +++++++++
37
38 **ffi.new(cdecl, init=None)**:
39 allocate an instance according to the specified C type and return a
40 pointer to it. The specified C type must be either a pointer or an
41 array: ``new('X *')`` allocates an X and returns a pointer to it,
42 whereas ``new('X[10]')`` allocates an array of 10 X'es and returns an
43 array referencing it (which works mostly like a pointer, like in C).
44 You can also use ``new('X[]', n)`` to allocate an array of a
45 non-constant length n. See the `detailed documentation`__ for other
46 valid initializers.
47
48 .. __: using.html#working
49
50 When the returned ``<cdata>`` object goes out of scope, the memory is
51 freed. In other words the returned ``<cdata>`` object has ownership of
52 the value of type ``cdecl`` that it points to. This means that the raw
53 data can be used as long as this object is kept alive, but must not be
54 used for a longer time. Be careful about that when copying the
55 pointer to the memory somewhere else, e.g. into another structure.
56 Also, this means that a line like ``x = ffi.cast("B *", ffi.new("A *"))``
57 or ``x = ffi.new("struct s[1]")[0]`` is wrong: the newly allocated object
58 goes out of scope instantly, and so is freed immediately, and ``x`` is
59 garbage. The only case where this is fine comes from a special case for
60 pointers-to-struct and pointers-to-union types: after
61 ``p = ffi.new("struct-or-union *", ..)``, then either ``p`` or ``p[0]``
62 keeps the memory alive.
63
64 The returned memory is initially cleared (filled with zeroes), before
65 the optional initializer is applied. For performance, see
66 `ffi.new_allocator()`_ for a way to allocate non-zero-initialized
67 memory.
68
69 *New in version 1.12:* see also ``ffi.release()``.
70
71
72 ffi.cast()
73 ++++++++++
74
75 **ffi.cast("C type", value)**: similar to a C cast: returns an
76 instance of the named C type initialized with the given value. The
77 value is casted between integers or pointers of any type.
78
79
80 .. _ffi-errno:
81 .. _ffi-getwinerror:
82
83 ffi.errno, ffi.getwinerror()
84 ++++++++++++++++++++++++++++
85
86 **ffi.errno**: the value of ``errno`` received from the most recent C call
87 in this thread, and passed to the following C call. (This is a thread-local
88 read-write property.)
89
90 **ffi.getwinerror(code=-1)**: on Windows, in addition to ``errno`` we
91 also save and restore the ``GetLastError()`` value across function
92 calls. This function returns this error code as a tuple ``(code,
93 message)``, adding a readable message like Python does when raising
94 WindowsError. If the argument ``code`` is given, format that code into
95 a message instead of using ``GetLastError()``.
96 (Note that it is also possible to declare and call the ``GetLastError()``
97 function as usual.)
98
99
100 .. _ffi-string:
101 .. _ffi-unpack:
102
103 ffi.string(), ffi.unpack()
104 ++++++++++++++++++++++++++
105
106 **ffi.string(cdata, [maxlen])**: return a Python string (or unicode
107 string) from the 'cdata'.
108
109 - If 'cdata' is a pointer or array of characters or bytes, returns the
110 null-terminated string. The returned string extends until the first
111 null character. The 'maxlen' argument limits how far we look for a
112 null character. If 'cdata' is an
113 array then 'maxlen' defaults to its length. See ``ffi.unpack()`` below
114 for a way to continue past the first null character. *Python 3:* this
115 returns a ``bytes``, not a ``str``.
116
117 - If 'cdata' is a pointer or array of wchar_t, returns a unicode string
118 following the same rules. *New in version 1.11:* can also be
119 char16_t or char32_t.
120
121 - If 'cdata' is a single character or byte or a wchar_t or charN_t,
122 returns it as a byte string or unicode string. (Note that in some
123 situation a single wchar_t or char32_t may require a Python unicode
124 string of length 2.)
125
126 - If 'cdata' is an enum, returns the value of the enumerator as a string.
127 If the value is out of range, it is simply returned as the stringified
128 integer.
129
130 **ffi.unpack(cdata, length)**: unpacks an array of C data of the given
131 length, returning a Python string/unicode/list. The 'cdata' should be
132 a pointer; if it is an array it is first converted to the pointer
133 type. *New in version 1.6.*
134
135 - If 'cdata' is a pointer to 'char', returns a byte string. It does
136 not stop at the first null. (An equivalent way to do that is
137 ``ffi.buffer(cdata, length)[:]``.)
138
139 - If 'cdata' is a pointer to 'wchar_t', returns a unicode string.
140 ('length' is measured in number of wchar_t; it is not the size in
141 bytes.) *New in version 1.11:* can also be char16_t or char32_t.
142
143 - If 'cdata' is a pointer to anything else, returns a list, of the
144 given 'length'. (A slower way to do that is ``[cdata[i] for i in
145 range(length)]``.)
146
147
148 .. _ffi-buffer:
149 .. _ffi-from-buffer:
150
151 ffi.buffer(), ffi.from_buffer()
152 +++++++++++++++++++++++++++++++
153
154 **ffi.buffer(cdata, [size])**: return a buffer object that references
155 the raw C data pointed to by the given 'cdata', of 'size' bytes. What
156 Python calls "a buffer", or more precisely "an object supporting the
157 buffer interface", is an object that represents some raw memory and
158 that can be passed around to various built-in or extension functions;
159 these built-in functions read from or write to the raw memory directly,
160 without needing an extra copy.
161
162 The 'cdata' argument
163 must be a pointer or an array. If unspecified, the size of the
164 buffer is either the size of what ``cdata`` points to, or the whole size
165 of the array.
166
167 Here are a few examples of where buffer() would be useful:
168
169 - use ``file.write()`` and ``file.readinto()`` with
170 such a buffer (for files opened in binary mode)
171
172 - overwrite the content of a struct: if ``p`` is a cdata pointing to
173 it, use ``ffi.buffer(p)[:] = newcontent``, where ``newcontent`` is
174 a bytes object (``str`` in Python 2).
175
176 Remember that like in C, you can use ``array + index`` to get the pointer
177 to the index'th item of an array. (In C you might more naturally write
178 ``&array[index]``, but that is equivalent.)
179
180 The returned object's type is not the builtin ``buffer`` nor ``memoryview``
181 types, because these types' API changes too much across Python versions.
182 Instead it has the following Python API (a subset of Python 2's ``buffer``)
183 in addition to supporting the buffer interface:
184
185 - ``buf[:]`` or ``bytes(buf)``: copy data out of the buffer, returning a
186 regular byte string (or ``buf[start:end]`` for a part)
187
188 - ``buf[:] = newstr``: copy data into the buffer (or ``buf[start:end]
189 = newstr``)
190
191 - ``len(buf)``, ``buf[index]``, ``buf[index] = newchar``: access as a sequence
192 of characters.
193
194 The buffer object returned by ``ffi.buffer(cdata)`` keeps alive the
195 ``cdata`` object: if it was originally an owning cdata, then its
196 owned memory will not be freed as long as the buffer is alive.
197
198 Python 2/3 compatibility note: you should avoid using ``str(buf)``,
199 because it gives inconsistent results between Python 2 and Python 3.
200 (This is similar to how ``str()`` gives inconsistent results on regular
201 byte strings). Use ``buf[:]`` instead.
202
203 *New in version 1.10:* ``ffi.buffer`` is now the type of the returned
204 buffer objects; ``ffi.buffer()`` actually calls the constructor.
205
206 **ffi.from_buffer([cdecl,] python_buffer, require_writable=False)**:
207 return an array cdata (by default a ``<cdata 'char[]'>``) that
208 points to the data of the given Python object, which must support the
209 buffer interface. Note that ``ffi.from_buffer()`` turns a generic
210 Python buffer object into a cdata object, whereas ``ffi.buffer()`` does
211 the opposite conversion. Both calls don't actually copy any data.
212
213 ``ffi.from_buffer()`` is meant to be used on objects
214 containing large quantities of raw data, like bytearrays
215 or ``array.array`` or numpy
216 arrays. It supports both the old *buffer* API (in Python 2.x) and the
217 new *memoryview* API. Note that if you pass a read-only buffer object,
218 you still get a regular ``<cdata 'char[]'>``; it is your responsibility
219 not to write there if the original buffer doesn't expect you to.
220 *In particular, never modify byte strings!*
221
222 The original object is kept alive (and, in case
223 of memoryview, locked) as long as the cdata object returned by
224 ``ffi.from_buffer()`` is alive.
225
226 A common use case is calling a C function with some ``char *`` that
227 points to the internal buffer of a Python object; for this case you
228 can directly pass ``ffi.from_buffer(python_buffer)`` as argument to
229 the call.
230
231 *New in version 1.10:* the ``python_buffer`` can be anything supporting
232 the buffer/memoryview interface (except unicode strings). Previously,
233 bytearray objects were supported in version 1.7 onwards (careful, if you
234 resize the bytearray, the ``<cdata>`` object will point to freed
235 memory); and byte strings were supported in version 1.8 onwards.
236
237 *New in version 1.12:* added the optional *first* argument ``cdecl``, and
238 the keyword argument ``require_writable``:
239
240 * ``cdecl`` defaults to ``"char[]"``, but a different array
241 or (from version 1.13) pointer type can be
242 specified for the result. A value like ``"int[]"`` will return an array of
243 ints instead of chars, and its length will be set to the number of ints
244 that fit in the buffer (rounded down if the division is not exact). Values
245 like ``"int[42]"`` or ``"int[2][3]"`` will return an array of exactly 42
246 (resp. 2-by-3) ints, raising a ValueError if the buffer is too small. The
247 difference between specifying ``"int[]"`` and using the older code ``p1 =
248 ffi.from_buffer(x); p2 = ffi.cast("int *", p1)`` is that the older code
249 needs to keep ``p1`` alive as long as ``p2`` is in use, because only ``p1``
250 keeps the underlying Python object alive and locked. (In addition,
251 ``ffi.from_buffer("int[]", x)`` gives better array bound checking.)
252
253 *New in version 1.13:* ``cdecl`` can be a pointer type. If it points
254 to a struct or union, you can, as usual, write ``p.field`` instead of
255 ``p[0].field``. You can also access ``p[n]``; note that CFFI does not
256 perform any bounds checking in this case. Note also that ``p[0]`` cannot
257 be used to keep the buffer alive (unlike what occurs with ``ffi.new()``).
258
259 * if ``require_writable`` is set to True, the function fails if the buffer
260 obtained from ``python_buffer`` is read-only (e.g. if ``python_buffer`` is
261 a byte string). The exact exception is raised by the object itself, and
262 for things like bytes it varies with the Python version, so don't rely on
263 it. (Before version 1.12, the same effect can be achieved with a hack:
264 call ``ffi.memmove(python_buffer, b"", 0)``. This has no effect if the
265 object is writable, but fails if it is read-only.) Please keep in mind
266 that CFFI does not implement the C keyword ``const``: even if you set
267 ``require_writable`` to False explicitly, you still get a regular
268 read-write cdata pointer.
269
270 *New in version 1.12:* see also ``ffi.release()``.
271
272
273 ffi.memmove()
274 +++++++++++++
275
276 **ffi.memmove(dest, src, n)**: copy ``n`` bytes from memory area
277 ``src`` to memory area ``dest``. See examples below. Inspired by the
278 C functions ``memcpy()`` and ``memmove()``---like the latter, the
279 areas can overlap. Each of ``dest`` and ``src`` can be either a cdata
280 pointer or a Python object supporting the buffer/memoryview interface.
281 In the case of ``dest``, the buffer/memoryview must be writable.
282 *New in version 1.3.* Examples:
283
284 * ``ffi.memmove(myptr, b"hello", 5)`` copies the 5 bytes of
285 ``b"hello"`` to the area that ``myptr`` points to.
286
287 * ``ba = bytearray(100); ffi.memmove(ba, myptr, 100)`` copies 100
288 bytes from ``myptr`` into the bytearray ``ba``.
289
290 * ``ffi.memmove(myptr + 1, myptr, 100)`` shifts 100 bytes from
291 the memory at ``myptr`` to the memory at ``myptr + 1``.
292
293 In versions before 1.10, ``ffi.from_buffer()`` had restrictions on the
294 type of buffer, which made ``ffi.memmove()`` more general.
295
296 .. _ffi-typeof:
297 .. _ffi-sizeof:
298 .. _ffi-alignof:
299
300 ffi.typeof(), ffi.sizeof(), ffi.alignof()
301 +++++++++++++++++++++++++++++++++++++++++
302
303 **ffi.typeof("C type" or cdata object)**: return an object of type
304 ``<ctype>`` corresponding to the parsed string, or to the C type of the
305 cdata instance. Usually you don't need to call this function or to
306 explicitly manipulate ``<ctype>`` objects in your code: any place that
307 accepts a C type can receive either a string or a pre-parsed ``ctype``
308 object (and because of caching of the string, there is no real
309 performance difference). It can still be useful in writing typechecks,
310 e.g.:
311
312 .. code-block:: python
313
314 def myfunction(ptr):
315 assert ffi.typeof(ptr) is ffi.typeof("foo_t*")
316 ...
317
318 Note also that the mapping from strings like ``"foo_t*"`` to the
319 ``<ctype>`` objects is stored in some internal dictionary. This
320 guarantees that there is only one ``<ctype 'foo_t *'>`` object, so you
321 can use the ``is`` operator to compare it. The downside is that the
322 dictionary entries are immortal for now. In the future, we may add
323 transparent reclamation of old, unused entries. In the meantime, note
324 that using strings like ``"int[%d]" % length`` to name a type will
325 create many immortal cached entries if called with many different
326 lengths.
327
328 **ffi.sizeof("C type" or cdata object)**: return the size of the
329 argument in bytes. The argument can be either a C type, or a cdata object,
330 like in the equivalent ``sizeof`` operator in C.
331
332 For ``array = ffi.new("T[]", n)``, then ``ffi.sizeof(array)`` returns
333 ``n * ffi.sizeof("T")``. *New in version 1.9:* Similar rules apply for
334 structures with a variable-sized array at the end. More precisely, if
335 ``p`` was returned by ``ffi.new("struct foo *", ...)``, then
336 ``ffi.sizeof(p[0])`` now returns the total allocated size. In previous
337 versions, it used to just return ``ffi.sizeof(ffi.typeof(p[0]))``, which
338 is the size of the structure ignoring the variable-sized part. (Note
339 that due to alignment, it is possible for ``ffi.sizeof(p[0])`` to return
340 a value smaller than ``ffi.sizeof(ffi.typeof(p[0]))``.)
341
342 **ffi.alignof("C type")**: return the natural alignment size in bytes of
343 the argument. Corresponds to the ``__alignof__`` operator in GCC.
344
345
346 .. _ffi-offsetof:
347 .. _ffi-addressof:
348
349 ffi.offsetof(), ffi.addressof()
350 +++++++++++++++++++++++++++++++
351
352 **ffi.offsetof("C struct or array type", \*fields_or_indexes)**: return the
353 offset within the struct of the given field. Corresponds to ``offsetof()``
354 in C.
355
356 You can give several field names in case of nested structures. You
357 can also give numeric values which correspond to array items, in case
358 of a pointer or array type. For example, ``ffi.offsetof("int[5]", 2)``
359 is equal to the size of two integers, as is ``ffi.offsetof("int *", 2)``.
360
361
362 **ffi.addressof(cdata, \*fields_or_indexes)**: limited equivalent to
363 the '&' operator in C:
364
365 1. ``ffi.addressof(<cdata 'struct-or-union'>)`` returns a cdata that
366 is a pointer to this struct or union. The returned pointer is only
367 valid as long as the original ``cdata`` object is; be sure to keep it
368 alive if it was obtained directly from ``ffi.new()``.
369
370 2. ``ffi.addressof(<cdata>, field-or-index...)`` returns the address
371 of a field or array item inside the given structure or array. In case
372 of nested structures or arrays, you can give more than one field or
373 index to look recursively. Note that ``ffi.addressof(array, index)``
374 can also be expressed as ``array + index``: this is true both in CFFI
375 and in C, where ``&array[index]`` is just ``array + index``.
376
377 3. ``ffi.addressof(<library>, "name")`` returns the address of the
378 named function or global variable from the given library object.
379 For functions, it returns a regular cdata
380 object containing a pointer to the function. Note that in API
381 mode, this is not the same as just writing `lib.funcname`: the latter
382 returns a special object that (before version 1.17) can
383 mostly only be called. *New in version 1.17:* you can now use
384 `lib.funcname` in many places where a `<cdata>` object was required,
385 so using `ffi.addressof(lib, "funcname")` is generally not needed any
386 more. For example, you can now pass `lib.funcname` as a callback to
387 a C function call, or write it inside a C structure field of the
388 correct pointer-to-function type, or use `ffi.cast()` or
389 `ffi.typeof()` on it.
390
391 Note that the case 1. cannot be used to take the address of a
392 primitive or pointer, but only a struct or union. It would be
393 difficult to implement because only structs and unions are internally
394 stored as an indirect pointer to the data. If you need a C int whose
395 address can be taken, use ``ffi.new("int[1]")`` in the first place;
396 similarly, for a pointer, use ``ffi.new("foo_t *[1]")``.
397
398
399 .. _ffi-cdata:
400 .. _ffi-ctype:
401
402 ffi.CData, ffi.CType
403 ++++++++++++++++++++
404
405 **ffi.CData, ffi.CType**: the Python type of the objects referred to
406 as ``<cdata>`` and ``<ctype>`` in the rest of this document. Note
407 that some cdata objects may be actually of a subclass of
408 ``ffi.CData``, and similarly with ctype, so you should check with
409 ``if isinstance(x, ffi.CData)``. Also, ``<ctype>`` objects have
410 a number of attributes for introspection: ``kind`` and ``cname`` are
411 always present, and depending on the kind they may also have
412 ``item``, ``length``, ``fields``, ``args``, ``result``, ``ellipsis``,
413 ``abi``, ``elements`` and ``relements``.
414
415 *New in version 1.10:* ``ffi.buffer`` is now `a type`__ as well.
416
417 .. __: #ffi-buffer
418
419
420 .. _ffi-gc:
421
422 ffi.gc()
423 ++++++++
424
425 **ffi.gc(cdata, destructor, size=0)**:
426 return a new cdata object that points to the
427 same data. Later, when this new cdata object is garbage-collected,
428 ``destructor(old_cdata_object)`` will be called. Example of usage:
429 ``ptr = ffi.gc(lib.custom_malloc(42), lib.custom_free)``.
430 Note that like objects
431 returned by ``ffi.new()``, the returned pointer objects have *ownership*,
432 which means the destructor is called as soon as *this* exact returned
433 object is garbage-collected.
434
435 *New in version 1.12:* see also ``ffi.release()``.
436
437 **ffi.gc(ptr, None, size=0)**:
438 removes the ownership on a object returned by a
439 regular call to ``ffi.gc``, and no destructor will be called when it
440 is garbage-collected. The object is modified in-place, and the
441 function returns ``None``. *New in version 1.7: ffi.gc(ptr, None)*
442
443 Note that ``ffi.gc()`` should be avoided for limited resources, or (with
444 cffi below 1.11) for large memory allocations. This is particularly
445 true on PyPy: its GC does not know how much memory or how many resources
446 the returned ``ptr`` holds. It will only run its GC when enough memory
447 it knows about has been allocated (and thus run the destructor possibly
448 later than you would expect). Moreover, the destructor is called in
449 whatever thread PyPy is at that moment, which might be a problem for
450 some C libraries. In these cases, consider writing a wrapper class with
451 custom ``__enter__()`` and ``__exit__()`` methods, allocating and
452 freeing the C data at known points in time, and using it in a ``with``
453 statement. In cffi 1.12, see also ``ffi.release()``.
454
455 *New in version 1.11:* the ``size`` argument. If given, this should be
456 an estimate of the size (in bytes) that ``ptr`` keeps alive. This
457 information is passed on to the garbage collector, fixing part of the
458 problem described above. The ``size`` argument is most important on
459 PyPy; on CPython, it is ignored so far, but in the future it could be
460 used to trigger more eagerly the cyclic reference GC, too (see CPython
461 `issue 31105`__).
462
463 The form ``ffi.gc(ptr, None, size=0)`` can be called with a negative
464 ``size``, to cancel the estimate. It is not mandatory, though:
465 nothing gets out of sync if the size estimates do not match. It only
466 makes the next GC start more or less early.
467
468 Note that if you have several ``ffi.gc()`` objects, the corresponding
469 destructors will be called in a random order. If you need a particular
470 order, see the discussion in `issue 340`__.
471
472 .. __: http://bugs.python.org/issue31105
473 .. __: https://foss.heptapod.net/pypy/cffi/-/issues/340
474
475
476 .. _ffi-new-handle:
477 .. _ffi-from-handle:
478
479 ffi.new_handle(), ffi.from_handle()
480 +++++++++++++++++++++++++++++++++++
481
482 **ffi.new_handle(python_object)**: return a non-NULL cdata of type
483 ``void *`` that contains an opaque reference to ``python_object``. You
484 can pass it around to C functions or store it into C structures. Later,
485 you can use **ffi.from_handle(p)** to retrieve the original
486 ``python_object`` from a value with the same ``void *`` pointer.
487 *Calling ffi.from_handle(p) is invalid and will likely crash if
488 the cdata object returned by new_handle() is not kept alive!*
489
490 See a `typical usage example`_ below.
491
492 (In case you are wondering, this ``void *`` is not the ``PyObject *``
493 pointer. This wouldn't make sense on PyPy anyway.)
494
495 The ``ffi.new_handle()/from_handle()`` functions *conceptually* work
496 like this:
497
498 * ``new_handle()`` returns cdata objects that contains references to
499 the Python objects; we call them collectively the "handle" cdata
500 objects. The ``void *`` value in these handle cdata objects are
501 random but unique.
502
503 * ``from_handle(p)`` searches all live "handle" cdata objects for the
504 one that has the same value ``p`` as its ``void *`` value. It then
505 returns the Python object referenced by that handle cdata object.
506 If none is found, you get "undefined behavior" (i.e. crashes).
507
508 The "handle" cdata object keeps the Python object alive, similar to
509 how ``ffi.new()`` returns a cdata object that keeps a piece of memory
510 alive. If the handle cdata object *itself* is not alive any more,
511 then the association ``void * -> python_object`` is dead and
512 ``from_handle()`` will crash.
513
514 *New in version 1.4:* two calls to ``new_handle(x)`` are guaranteed to
515 return cdata objects with different ``void *`` values, even with the
516 same ``x``. This is a useful feature that avoids issues with unexpected
517 duplicates in the following trick: if you need to keep alive the
518 "handle" until explicitly asked to free it, but don't have a natural
519 Python-side place to attach it to, then the easiest is to ``add()`` it
520 to a global set. It can later be removed from the set by
521 ``global_set.discard(p)``, with ``p`` any cdata object whose ``void *``
522 value compares equal.
523
524 .. _`typical usage example`:
525
526 Usage example: suppose you have a C library where you must call a
527 ``lib.process_document()`` function which invokes some callback. The
528 ``process_document()`` function receives a pointer to a callback and a
529 ``void *`` argument. The callback is then invoked with the ``void
530 *data`` argument that is equal to the provided value. In this typical
531 case, you can implement it like this (out-of-line API mode)::
532
533 class MyDocument:
534 ...
535
536 def process(self):
537 h = ffi.new_handle(self)
538 lib.process_document(lib.my_callback, # the callback
539 h, # 'void *data'
540 args...)
541 # 'h' stays alive until here, which means that the
542 # ffi.from_handle() done in my_callback() during
543 # the call to process_document() is safe
544
545 def callback(self, arg1, arg2):
546 ...
547
548 # the actual callback is this one-liner global function:
549 @ffi.def_extern()
550 def my_callback(arg1, arg2, data):
551 return ffi.from_handle(data).callback(arg1, arg2)
552
553
554 .. _ffi-dlopen:
555 .. _ffi-dlclose:
556
557 ffi.dlopen(), ffi.dlclose()
558 +++++++++++++++++++++++++++
559
560 **ffi.dlopen(libpath, [flags])**: opens and returns a "handle" to a
561 dynamic library, as a ``<lib>`` object. See `Preparing and
562 Distributing modules`_.
563
564 **ffi.dlclose(lib)**: explicitly closes a ``<lib>`` object returned
565 by ``ffi.dlopen()``.
566
567 **ffi.RLTD_...**: constants: flags for ``ffi.dlopen()``.
568
569
570 ffi.new_allocator()
571 +++++++++++++++++++
572
573 **ffi.new_allocator(alloc=None, free=None, should_clear_after_alloc=True)**:
574 returns a new allocator. An "allocator" is a callable that behaves like
575 ``ffi.new()`` but uses the provided low-level ``alloc`` and ``free``
576 functions. *New in version 1.2.*
577
578 ``alloc()`` is invoked with the size as sole argument. If it returns
579 NULL, a MemoryError is raised. Later, if ``free`` is not None, it will
580 be called with the result of ``alloc()`` as argument. Both can be either
581 Python function or directly C functions. If only ``free`` is None, then no
582 free function is called. If both ``alloc`` and ``free`` are None, the
583 default alloc/free combination is used. (In other words, the call
584 ``ffi.new(*args)`` is equivalent to ``ffi.new_allocator()(*args)``.)
585
586 If ``should_clear_after_alloc`` is set to False, then the memory
587 returned by ``alloc()`` is assumed to be already cleared (or you are
588 fine with garbage); otherwise CFFI will clear it. Example: for
589 performance, if you are using ``ffi.new()`` to allocate large chunks of
590 memory where the initial content can be left uninitialized, you can do::
591
592 # at module level
593 new_nonzero = ffi.new_allocator(should_clear_after_alloc=False)
594
595 # then replace `p = ffi.new("char[]", bigsize)` with:
596 p = new_nonzero("char[]", bigsize)
597
598 **NOTE:** the following is a general warning that applies particularly
599 (but not only) to PyPy versions 5.6 or older (PyPy > 5.6 attempts to
600 account for the memory returned by ``ffi.new()`` or a custom allocator;
601 and CPython uses reference counting). If you do large allocations, then
602 there is no hard guarantee about when the memory will be freed. You
603 should avoid both ``new()`` and ``new_allocator()()`` if you want to be
604 sure that the memory is promptly released, e.g. before you allocate more
605 of it.
606
607 An alternative is to declare and call the C ``malloc()`` and ``free()``
608 functions, or some variant like ``mmap()`` and ``munmap()``. Then you
609 control exactly when the memory is allocated and freed. For example,
610 add these two lines to your existing ``ffibuilder.cdef()``::
611
612 void *malloc(size_t size);
613 void free(void *ptr);
614
615 and then call these two functions manually::
616
617 p = lib.malloc(n * ffi.sizeof("int"))
618 try:
619 my_array = ffi.cast("int *", p)
620 ...
621 finally:
622 lib.free(p)
623
624 In cffi version 1.12 you can indeed use ``ffi.new_allocator()`` but use the
625 ``with`` statement (see ``ffi.release()``) to force the free function to be
626 called at a known point. The above is equivalent to this code::
627
628 my_new = ffi.new_allocator(lib.malloc, lib.free) # at global level
629 ...
630 with my_new("int[]", n) as my_array:
631 ...
632
633 **Warning:** due to a bug, ``p = ffi.new_allocator(..)("struct-or-union *")``
634 might not follow the rule that either ``p`` or ``p[0]`` keeps the memory
635 alive, which holds for the normal ``ffi.new("struct-or-union *")`` allocator.
636 It may sometimes be the case that if there is only a reference to ``p[0]``,
637 the memory is freed. The cause is that the rule doesn't hold for
638 ``ffi.gc()``, which is sometimes used in the implementation of
639 ``ffi.new_allocator()()``; this might be fixed in a future release.
640
641
642 .. _ffi-release:
643
644 ffi.release() and the context manager
645 +++++++++++++++++++++++++++++++++++++
646
647 **ffi.release(cdata)**: release the resources held by a cdata object from
648 ``ffi.new()``, ``ffi.gc()``, ``ffi.from_buffer()`` or
649 ``ffi.new_allocator()()``. The cdata object must not be used afterwards.
650 The normal Python destructor of the cdata object releases the same resources,
651 but this allows the releasing to occur at a known time, as opposed as at an
652 unspecified point in the future.
653 *New in version 1.12.*
654
655 ``ffi.release(cdata)`` is equivalent to ``cdata.__exit__()``, which means that
656 you can use the ``with`` statement to ensure that the cdata is released at the
657 end of a block (in version 1.12 and above)::
658
659 with ffi.from_buffer(...) as p:
660 do something with p
661
662 The effect is more precisely as follows:
663
664 * on an object returned from ``ffi.gc(destructor)``, ``ffi.release()`` will
665 cause the ``destructor`` to be called immediately.
666
667 * on an object returned from a custom allocator, the custom free function
668 is called immediately.
669
670 * on CPython, ``ffi.from_buffer(buf)`` locks the buffer, so ``ffi.release()``
671 can be used to unlock it at a known time. On PyPy, there is no locking
672 (so far); the effect of ``ffi.release()`` is limited to removing the link,
673 allowing the original buffer object to be garbage-collected even if the
674 cdata object stays alive.
675
676 * on CPython this method has no effect (so far) on objects returned by
677 ``ffi.new()``, because the memory is allocated inline with the cdata object
678 and cannot be freed independently. It might be fixed in future releases of
679 cffi.
680
681 * on PyPy, ``ffi.release()`` frees the ``ffi.new()`` memory immediately. It is
682 useful because otherwise the memory is kept alive until the next GC occurs.
683 If you allocate large amounts of memory with ``ffi.new()`` and don't free
684 them with ``ffi.release()``, PyPy (>= 5.7) runs its GC more often to
685 compensate, so the total memory allocated should be kept within bounds
686 anyway; but calling ``ffi.release()`` explicitly should improve performance
687 by reducing the frequency of GC runs.
688
689 After ``ffi.release(x)``, do not use anything pointed to by ``x`` any longer.
690 As an exception to this rule, you can call ``ffi.release(x)`` several times
691 for the exact same cdata object ``x``; the calls after the first one are
692 ignored.
693
694
695 ffi.init_once()
696 +++++++++++++++
697
698 **ffi.init_once(function, tag)**: run ``function()`` once. The
699 ``tag`` should be a primitive object, like a string, that identifies
700 the function: ``function()`` is only called the first time we see the
701 ``tag``. The return value of ``function()`` is remembered and
702 returned by the current and all future ``init_once()`` with the same
703 tag. If ``init_once()`` is called from multiple threads in parallel,
704 all calls block until the execution of ``function()`` is done. If
705 ``function()`` raises an exception, it is propagated and nothing is
706 cached (i.e. ``function()`` will be called again, in case we catch the
707 exception and try ``init_once()`` again). *New in version 1.4.*
708
709 Example::
710
711 from _xyz_cffi import ffi, lib
712
713 def initlib():
714 lib.init_my_library()
715
716 def make_new_foo():
717 ffi.init_once(initlib, "init")
718 return lib.make_foo()
719
720 ``init_once()`` is optimized to run very quickly if ``function()`` has
721 already been called. (On PyPy, the cost is zero---the JIT usually
722 removes everything in the machine code it produces.)
723
724 *Note:* one motivation__ for ``init_once()`` is the CPython notion of
725 "subinterpreters" in the embedded case. If you are using the
726 out-of-line API mode, ``function()`` is called only once even in the
727 presence of multiple subinterpreters, and its return value is shared
728 among all subinterpreters. The goal is to mimic the way traditional
729 CPython C extension modules have their init code executed only once in
730 total even if there are subinterpreters. In the example above, the C
731 function ``init_my_library()`` is called once in total, not once per
732 subinterpreter. For this reason, avoid Python-level side-effects in
733 ``function()`` (as they will only be applied in the first
734 subinterpreter to run); instead, return a value, as in the following
735 example::
736
737 def init_get_max():
738 return lib.initialize_once_and_get_some_maximum_number()
739
740 def process(i):
741 if i > ffi.init_once(init_get_max, "max"):
742 raise IndexError("index too large!")
743 ...
744
745 .. __: https://foss.heptapod.net/pypy/cffi/-/issues/233
746
747
748 .. _ffi-getctype:
749 .. _ffi-list-types:
750
751 ffi.getctype(), ffi.list_types()
752 ++++++++++++++++++++++++++++++++
753
754 **ffi.getctype("C type" or <ctype>, extra="")**: return the string
755 representation of the given C type. If non-empty, the "extra" string is
756 appended (or inserted at the right place in more complicated cases); it
757 can be the name of a variable to declare, or an extra part of the type
758 like ``"*"`` or ``"[5]"``. For example
759 ``ffi.getctype(ffi.typeof(x), "*")`` returns the string representation
760 of the C type "pointer to the same type than x"; and
761 ``ffi.getctype("char[80]", "a") == "char a[80]"``.
762
763 **ffi.list_types()**: Returns the user type names known to this FFI
764 instance. This returns a tuple containing three lists of names:
765 ``(typedef_names, names_of_structs, names_of_unions)``. *New in
766 version 1.6.*
767
768
769 .. _`Preparing and Distributing modules`: cdef.html#loading-libraries
770
771
772 Conversions
773 -----------
774
775 This section documents all the conversions that are allowed when
776 *writing into* a C data structure (or passing arguments to a function
777 call), and *reading from* a C data structure (or getting the result of a
778 function call). The last column gives the type-specific operations
779 allowed.
780
781 +---------------+------------------------+------------------+----------------+
782 | C type | writing into | reading from |other operations|
783 +===============+========================+==================+================+
784 | integers | an integer or anything | a Python int or | int(), bool() |
785 | and enums | on which int() works | long, depending | `[6]`, |
786 | `[5]` | (but not a float!). | on the type | ``<`` |
787 | | Must be within range. | (ver. 1.10: or a | |
788 | | | bool) | |
789 +---------------+------------------------+------------------+----------------+
790 | ``char`` | a string of length 1 | a string of | int(), bool(), |
791 | | or another <cdata char>| length 1 | ``<`` |
792 +---------------+------------------------+------------------+----------------+
793 | ``wchar_t``, | a unicode of length 1 | a unicode of | |
794 | ``char16_t``, | (or maybe 2 if | length 1 | int(), |
795 | ``char32_t`` | surrogates) or | (or maybe 2 if | bool(), ``<`` |
796 | `[8]` | another similar <cdata>| surrogates) | |
797 +---------------+------------------------+------------------+----------------+
798 | ``float``, | a float or anything on | a Python float | float(), int(),|
799 | ``double`` | which float() works | | bool(), ``<`` |
800 +---------------+------------------------+------------------+----------------+
801 |``long double``| another <cdata> with | a <cdata>, to | float(), int(),|
802 | | a ``long double``, or | avoid losing | bool() |
803 | | anything on which | precision `[3]` | |
804 | | float() works | | |
805 +---------------+------------------------+------------------+----------------+
806 | ``float`` | a complex number | a Python complex | complex(), |
807 | ``_Complex``, | or anything on which | number | bool() |
808 | ``double`` | complex() works | | `[7]` |
809 | ``_Complex`` | | | |
810 +---------------+------------------------+------------------+----------------+
811 | pointers | another <cdata> with | a <cdata> |``[]`` `[4]`, |
812 | | a compatible type (i.e.| |``+``, ``-``, |
813 | | same type | |bool() |
814 | | or ``void*``, or as an | | |
815 | | array instead) `[1]` | | |
816 +---------------+------------------------+ | |
817 | ``void *`` | another <cdata> with | | |
818 | | any pointer or array | | |
819 | | type, or `[9]` | | |
820 +---------------+------------------------+ +----------------+
821 | pointers to | same as pointers | | ``[]``, ``+``, |
822 | structure or | | | ``-``, bool(), |
823 | union | | | and read/write |
824 | | | | struct fields |
825 +---------------+------------------------+ +----------------+
826 | function | same as pointers, | | bool(), |
827 | pointers | or `[9]` | | call `[2]` |
828 +---------------+------------------------+------------------+----------------+
829 | arrays | a list or tuple of | a <cdata> |len(), iter(), |
830 | | items | |``[]`` `[4]`, |
831 | | | |``+``, ``-`` |
832 +---------------+------------------------+ +----------------+
833 | ``char[]``, | same as arrays, or a | | len(), iter(), |
834 | ``un/signed`` | Python byte string | | ``[]``, ``+``, |
835 | ``char[]``, | | | ``-`` |
836 | ``_Bool[]`` | | | |
837 +---------------+------------------------+ +----------------+
838 |``wchar_t[]``, | same as arrays, or a | | len(), iter(), |
839 |``char16_t[]``,| Python unicode string | | ``[]``, |
840 |``char32_t[]`` | | | ``+``, ``-`` |
841 | | | | |
842 +---------------+------------------------+------------------+----------------+
843 | structure | a list or tuple or | a <cdata> | read/write |
844 | | dict of the field | | fields |
845 | | values, or a same-type | | |
846 | | <cdata> | | |
847 +---------------+------------------------+ +----------------+
848 | union | same as struct, but | | read/write |
849 | | with at most one field | | fields |
850 +---------------+------------------------+------------------+----------------+
851
852 `[1]` ``item *`` is ``item[]`` in function arguments:
853
854 In a function declaration, as per the C standard, a ``item *``
855 argument is identical to a ``item[]`` argument (and ``ffi.cdef()``
856 doesn't record the difference). So when you call such a function,
857 you can pass an argument that is accepted by either C type, like
858 for example passing a Python byte string to a ``char *`` argument
859 (because it works for ``char[]`` arguments) or a list of integers
860 to a ``int *`` argument (it works for ``int[]`` arguments). Note
861 that even if you want to pass a single ``item``, you need to
862 specify it in a list of length 1; for example, a ``struct point_s
863 *`` argument might be passed as ``[[x, y]]`` or ``[{'x': 5, 'y':
864 10}]``. In all these cases (including passing a byte string to
865 a ``char *`` argument), the required C data structure is created
866 just before the call is done, and freed afterwards.
867
868 As an optimization, CFFI assumes that a
869 function with a ``char *`` argument to which you pass a Python byte
870 string will not actually modify the array of characters passed in,
871 and so it attempts to pass directly a pointer inside the Python
872 byte string object. This still doesn't mean that the ``char *``
873 argument can be stored by the C function and inspected later.
874 The ``char *`` is only valid for the duration of the call, even if
875 the Python object is kept alive for longer.
876 (On PyPy, this optimization is only available since PyPy 5.4
877 with CFFI 1.8. It may fail in rare cases and fall back to making
878 a copy anyway, but only for short strings so it shouldn't be
879 noticeable.)
880
881 If you need to pass a ``char *`` that must be valid for longer than
882 just the call, you need to build it explicitly, either with ``p =
883 ffi.new("char[]", mystring)`` (which makes a copy) or by not using a
884 byte string in the first place but something else like a buffer object,
885 or a bytearray and ``ffi.from_buffer()``; or just use
886 ``ffi.new("char[]", length)`` directly if possible.
887
888 `[2]` C function calls are done with the GIL released.
889
890 Note that we assume that the called functions are *not* using the
891 Python API from Python.h. For example, we don't check afterwards
892 if they set a Python exception. You may work around it, but mixing
893 CFFI with ``Python.h`` is not recommended. (If you do that, on
894 PyPy and on some platforms like Windows, you may need to explicitly
895 link to ``libpypy-c.dll`` to access the CPython C API compatibility
896 layer; indeed, CFFI-generated modules on PyPy don't link to
897 ``libpypy-c.dll`` on their own. But really, don't do that in the
898 first place.)
899
900 `[3]` ``long double`` support:
901
902 We keep ``long double`` values inside a cdata object to avoid
903 losing precision. Normal Python floating-point numbers only
904 contain enough precision for a ``double``. If you really want to
905 convert such an object to a regular Python float (i.e. a C
906 ``double``), call ``float()``. If you need to do arithmetic on
907 such numbers without any precision loss, you need instead to define
908 and use a family of C functions like ``long double add(long double
909 a, long double b);``.
910
911 `[4]` Slicing with ``x[start:stop]``:
912
913 Slicing is allowed, as long as you specify explicitly both ``start``
914 and ``stop`` (and don't give any ``step``). It gives a cdata
915 object that is a "view" of all items from ``start`` to ``stop``.
916 It is a cdata of type "array" (so e.g. passing it as an argument to a
917 C function would just convert it to a pointer to the ``start`` item).
918 As with indexing, negative bounds mean really negative indices, like in
919 C. As for slice assignment, it accepts any iterable, including a list
920 of items or another array-like cdata object, but the length must match.
921 (Note that this behavior differs from initialization: e.g. you can
922 say ``chararray[10:15] = "hello"``, but the assigned string must be of
923 exactly the correct length; no implicit null character is added.)
924
925 `[5]` Enums are handled like ints:
926
927 Like C, enum types are mostly int types (unsigned or signed, int or
928 long; note that GCC's first choice is unsigned). Reading an enum
929 field of a structure, for example, returns you an integer. To
930 compare their value symbolically, use code like ``if x.field ==
931 lib.FOO``. If you really want to get their value as a string, use
932 ``ffi.string(ffi.cast("the_enum_type", x.field))``.
933
934 `[6]` bool() on a primitive cdata:
935
936 *New in version 1.7.* In previous versions, it only worked on
937 pointers; for primitives it always returned True.
938
939 *New in version 1.10:* The C type ``_Bool`` or ``bool`` converts to
940 Python booleans now. You get an exception if a C ``_Bool`` happens
941 to contain a value different from 0 and 1 (this case triggers
942 undefined behavior in C; if you really have to interface with a
943 library relying on this, don't use ``_Bool`` in the CFFI side).
944 Also, when converting from a byte string to a ``_Bool[]``, only the
945 bytes ``\x00`` and ``\x01`` are accepted.
946
947 `[7]` libffi does not support complex numbers:
948
949 *New in version 1.11:* CFFI now supports complex numbers directly.
950 Note however that libffi does not. This means that C functions that
951 take directly as argument types or return type a complex type cannot
952 be called by CFFI, unless they are directly using the API mode.
953
954 *New in version 1.17:* CFFI now supports complex numbers with MSVC
955 on Windows. The types are called ``_Fcomplex`` (with floats) and
956 ``_Dcomplex`` (with doubles). You can use these types or still use
957 ``float _Complex`` and ``double _Complex`` for cross-platform convenience
958 in all places except ``set_source()``. With MSVC, the C code you pass to
959 ``set_source()`` must use ``_Fcomplex`` and ``_Dcomplex`` and
960 it must contain directly or indirectly ``#include <complex.h>``, like
961 normal C code. (CFFI also defines semi-internal macros
962 ``_cffi_float_complex_t`` and ``_cffi_double_complex_t`` which could
963 possibly be directly used.)
964
965 `[8]` ``wchar_t``, ``char16_t`` and ``char32_t``
966
967 See `Unicode character types`_ below.
968
969 `[9]` API-mode function from `lib.myfunc`:
970
971 In API mode, when you get a function from a C library by writing
972 `fn = lib.myfunc`, you get an object of a special type for performance
973 reasons, instead of a `<cdata 'C-function-type'>`. Before version 1.17
974 you could only call such objects. You could write
975 `ffi.addressof(lib, "myfunc")` in order to get a real `<cdata>` object,
976 based on the idea that in these cases in C you'd usually write `&myfunc`
977 instead of `myfunc`. *New in version 1.17:* the special object
978 `lib.myfunc` can now be passed in many places where CFFI expects
979 a regular `<cdata>` object. For example, you can now pass
980 it as a callback to a C function call, or write it inside a C
981 structure field of the correct pointer-to-function type, or use
982 `ffi.cast()` or `ffi.typeof()` on it.
983
984 .. _file:
985
986 Support for FILE
987 ++++++++++++++++
988
989 You can declare C functions taking a ``FILE *`` argument and
990 call them with a Python file object. If needed, you can also do ``c_f
991 = ffi.cast("FILE *", fileobj)`` and then pass around ``c_f``.
992
993 Note, however, that CFFI does this by a best-effort approach. If you
994 need finer control over buffering, flushing, and timely closing of the
995 ``FILE *``, then you should not use this special support for ``FILE *``.
996 Instead, you can handle regular ``FILE *`` cdata objects that you
997 explicitly make using fdopen(), like this:
998
999 .. code-block:: python
1000
1001 ffi.cdef('''
1002 FILE *fdopen(int, const char *); // from the C <stdio.h>
1003 int fclose(FILE *);
1004 ''')
1005
1006 myfile.flush() # make sure the file is flushed
1007 newfd = os.dup(myfile.fileno()) # make a copy of the file descriptor
1008 fp = lib.fdopen(newfd, "w") # make a cdata 'FILE *' around newfd
1009 lib.write_stuff_to_file(fp) # invoke the external function
1010 lib.fclose(fp) # when you're done, close fp (and newfd)
1011
1012 The special support for ``FILE *`` is anyway implemented in a similar manner
1013 on CPython 3.x and on PyPy, because these Python implementations' files are
1014 not natively based on ``FILE *``. Doing it explicitly offers more control.
1015
1016
1017 .. _unichar:
1018
1019 Unicode character types
1020 +++++++++++++++++++++++
1021
1022 The ``wchar_t`` type has the same signedness as the underlying
1023 platform's. For example, on Linux, it is a signed 32-bit integer.
1024 However, the types ``char16_t`` and ``char32_t`` (*new in version 1.11*)
1025 are always unsigned.
1026
1027 Note that CFFI assumes that these types are meant to contain UTF-16 or
1028 UTF-32 characters in the native endianness. More precisely:
1029
1030 * ``char32_t`` is assumed to contain UTF-32, or UCS4, which is just the
1031 unicode codepoint;
1032
1033 * ``char16_t`` is assumed to contain UTF-16, i.e. UCS2 plus surrogates;
1034
1035 * ``wchar_t`` is assumed to contain either UTF-32 or UTF-16 based on its
1036 actual platform-defined size of 4 or 2 bytes.
1037
1038 Whether this assumption is true or not is unspecified by the C language.
1039 In theory, the C library you are interfacing with could use one of these
1040 types with a different meaning. You would then need to handle it
1041 yourself---for example, by using ``uint32_t`` instead of ``char32_t`` in
1042 the ``cdef()``, and building the expected arrays of ``uint32_t``
1043 manually.
1044
1045 Python itself can be compiled with ``sys.maxunicode == 65535`` or
1046 ``sys.maxunicode == 1114111`` (Python >= 3.3 is always 1114111). This
1047 changes the handling of surrogates (which are pairs of 16-bit
1048 "characters" which actually stand for a single codepoint whose value is
1049 greater than 65535). If your Python is ``sys.maxunicode == 1114111``,
1050 then it can store arbitrary unicode codepoints; surrogates are
1051 automatically inserted when converting from Python unicodes to UTF-16,
1052 and automatically removed when converting back. On the other hand, if
1053 your Python is ``sys.maxunicode == 65535``, then it is the other way
1054 around: surrogates are removed when converting from Python unicodes
1055 to UTF-32, and added when converting back. In other words, surrogate
1056 conversion is done only when there is a size mismatch.
1057
1058 Note that Python's internal representations is not specified. For
1059 example, on CPython >= 3.3, it will use 1- or 2- or 4-bytes arrays
1060 depending on what the string actually contains. With CFFI, when you
1061 pass a Python byte string to a C function expecting a ``char*``, then
1062 we pass directly a pointer to the existing data without needing a
1063 temporary buffer; however, the same cannot cleanly be done with
1064 *unicode* string arguments and the ``wchar_t*`` / ``char16_t*`` /
1065 ``char32_t*`` types, because of the changing internal
1066 representation. As a result, and for consistency, CFFI always allocates
1067 a temporary buffer for unicode strings.
1068
1069 **Warning:** for now, if you use ``char16_t`` and ``char32_t`` with
1070 ``set_source()``, you have to make sure yourself that the types are
1071 declared by the C source you provide to ``set_source()``. They would be
1072 declared if you ``#include`` a library that explicitly uses them, for
1073 example, or when using C++11. Otherwise, you need ``#include
1074 <uchar.h>`` on Linux, or more generally something like ``typedef
1075 uint16_t char16_t;``. This is not done automatically by CFFI because
1076 ``uchar.h`` is not standard across platforms, and writing a ``typedef``
1077 like above would crash if the type happens to be already defined.