Debian Codegraph @

doc/source/cdef.rst

raw
1 =========================
2 Preparing Wrapper Modules
3 =========================
4
5 .. contents::
6
7 .. note::
8
9 A *wrapper module* is a Python module that uses CFFI to expose
10 functions and data from a C library, so that the rest of your
11 program can import it and call the library through the ``ffi`` and
12 ``lib`` objects. This page covers how to create wrapper modules.
13 See :ref:`cffi_gen_src_docs` for instructions on generating C source
14 code for wrapper modules.
15
16 There are three or four different ways to use CFFI in a project.
17 In order of complexity:
18
19 * The **"in-line", "ABI mode"**:
20
21 .. code-block:: python
22
23 import cffi
24
25 ffi = cffi.FFI()
26 ffi.cdef("C-like declarations")
27 lib = ffi.dlopen("libpath")
28
29 # use ffi and lib here
30
31 .. _out-of-line-abi:
32
33 * The **"out-of-line",** but still **"ABI mode",** useful to organize
34 the code and reduce the import time:
35
36 .. code-block:: python
37
38 # in a separate file "package/foo_build.py"
39 import cffi
40
41 ffibuilder = cffi.FFI()
42 ffibuilder.set_source("package._foo", None)
43 ffibuilder.cdef("C-like declarations")
44
45 if __name__ == "__main__":
46 ffibuilder.compile()
47
48 Running ``python foo_build.py`` produces a file ``_foo.py``, which
49 can then be imported in the main program:
50
51 .. code-block:: python
52
53 from package._foo import ffi
54 lib = ffi.dlopen("libpath")
55
56 # use ffi and lib here
57
58 .. _out-of-line-api:
59
60 * The **"out-of-line", "API mode"** gives you the most flexibility
61 and speed to access a C library at the level of C, instead of at the
62 binary level:
63
64 .. code-block:: python
65
66 # in a separate file "package/foo_build.py"
67 import cffi
68
69 ffibuilder = cffi.FFI()
70 ffibuilder.set_source("package._foo", r"""real C code""") # <=
71 ffibuilder.cdef("C-like declarations with '...'")
72
73 if __name__ == "__main__":
74 ffibuilder.compile(verbose=True)
75
76 Running ``python foo_build.py`` produces a file ``_foo.c`` and
77 invokes the C compiler to turn it into a file ``_foo.so`` (or
78 ``_foo.pyd`` or ``_foo.dylib``). It is a C extension module which
79 can be imported in the main program:
80
81 .. code-block:: python
82
83 from package._foo import ffi, lib
84 # no ffi.dlopen()
85
86 # use ffi and lib here
87
88
89 .. _cdef:
90
91 ffi/ffibuilder.cdef(): declaring types and functions
92 ----------------------------------------------------
93
94 **ffi/ffibuilder.cdef(source)**: parses the given C source.
95 It registers all the functions, types, constants and global variables in
96 the C source. The types can be used immediately in ``ffi.new()`` and
97 other functions. Before you can access the functions and global
98 variables, you need to give ``ffi`` another piece of information: where
99 they actually come from (which you do with either ``ffi.dlopen()`` or
100 ``ffi.set_source()``).
101
102 .. _`all types listed above`:
103
104 The C source is parsed internally (using ``pycparser``). This code
105 cannot contain ``#include``. It should typically be a self-contained
106 piece of declarations extracted from a man page. The only things it
107 can assume to exist are the standard types:
108
109 * char, short, int, long, long long (both signed and unsigned)
110
111 * float, double, long double
112
113 * intN_t, uintN_t (for N=8,16,32,64), intptr_t, uintptr_t, ptrdiff_t,
114 size_t, ssize_t
115
116 * wchar_t (if supported by the backend). *New in version 1.11:*
117 char16_t and char32_t.
118
119 * _Bool and bool (equivalent). If not directly supported by the C
120 compiler, this is declared with the size of ``unsigned char``.
121
122 * FILE. `See here.`__
123
124 * all `common Windows types`_ are defined if you run
125 on Windows (``DWORD``, ``LPARAM``, etc.). Exception:
126 ``TBYTE TCHAR LPCTSTR PCTSTR LPTSTR PTSTR PTBYTE PTCHAR`` are
127 not automatically defined; see `ffi.set_unicode()`_.
128
129 * the other standard integer types from
130 stdint.h, like ``intmax_t``, as long as they map to integers of 1,
131 2, 4 or 8 bytes. Larger integers are not supported.
132
133 .. __: ref.html#file
134 .. _`common Windows types`: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
135
136 The declarations can also contain "``...``" at various places; these are
137 placeholders that will be completed by the compiler. More information
138 about it below in `Letting the C compiler fill the gaps`_.
139
140 Note that all standard type names listed above are handled as
141 *defaults* only (apart from the ones that are keywords in the C
142 language). If your ``cdef`` contains an explicit typedef that
143 redefines one of the types above, then the default described above is
144 ignored. (This is a bit hard to implement cleanly, so in some corner
145 cases it might fail, notably with the error ``Multiple type specifiers
146 with a type tag``. Please report it as a bug if it does.)
147
148 Multiple calls to ``ffi.cdef()`` are possible. Beware that it can be
149 slow to call ``ffi.cdef()`` a lot of times, a consideration that is
150 important mainly in in-line mode.
151
152 The ``ffi.cdef()`` call optionally takes an extra argument: either
153 ``packed`` or ``pack``. If you pass ``packed=True``,
154 then all structs declared within
155 this cdef are "packed". (If you need both packed and non-packed
156 structs, use several cdefs in sequence.) This
157 has a meaning similar to ``__attribute__((packed))`` in GCC. It
158 specifies that all structure fields should have an alignment of one
159 byte. (Note that the packed attribute has no effect on bit fields so
160 far, which mean that they may be packed differently than on GCC.
161 Also, this has no effect on structs declared with ``"...;"``---more
162 about it later in `Letting the C compiler fill the gaps`_. In
163 particular, if your C source uses other attributes like
164 ``__attribute__((aligned(16)))``, there is no way to declare this fact
165 in the ``cdef()``, but you can generally just declare the struct with
166 ``"...;"`` as the last field.)
167
168 *New in version 1.12:* In ABI mode, you can also pass ``pack=n``,
169 with an integer ``n`` which must be a power of two. Then the
170 alignment of any field is limited to ``n`` if it would otherwise be
171 greater than ``n``. Passing ``pack=1`` is equivalent to passing
172 ``packed=True``. This is meant to emulate ``#pragma pack(n)`` from
173 the MSVC compiler. On Windows, the default is ``pack=8`` (from cffi
174 1.12 onwards); on other platforms, the default is ``pack=None``.
175
176 Note that you can use the type-qualifiers ``const`` and ``restrict``
177 (but not ``__restrict`` or ``__restrict__``) in the ``cdef()``, but
178 this has no effect on the cdata objects that you get at run-time (they
179 are never ``const``). The effect is limited to knowing if a global
180 variable is meant to be a constant or not. Also, *new in version
181 1.3:* when using ``set_source()`` or ``verify()``, these two
182 qualifiers are copied from the cdef to the generated C code; this
183 fixes warnings by the C compiler.
184
185 Note a trick if you copy-paste code from sources in which there are
186 extra macros (for example, the Windows documentation uses SAL
187 annotations like ``_In_`` or ``_Out_``). These hints must be removed
188 in the string given to cdef(), but it can be done programmatically
189 like this::
190
191 ffi.cdef(re.sub(r"\b(_In_|_Inout_|_Out_|_Outptr_)(opt_)?\b", " ",
192 """
193 DWORD WINAPI GetModuleFileName(
194 _In_opt_ HMODULE hModule,
195 _Out_ LPTSTR lpFilename,
196 _In_ DWORD nSize
197 );
198 """))
199
200 Note also that pycparser, the underlying C parser, recognizes
201 preprocessor-like directives in the following format: ``# NUMBER
202 "FILE"``. For example, if you put ``# 42 "foo.h"`` in the middle of the
203 string passed to ``cdef()`` and there is an error two lines later, then
204 it is reported with an error message that starts with ``foo.h:43:`` (the
205 line which is given the number 42 is the line immediately after the
206 directive). *New in version 1.10.1:* CFFI automatically puts the line
207 ``# 1 "<cdef source string>"`` just before the string you give to
208 ``cdef()``.
209
210
211 .. _`ffi.set_unicode()`:
212
213 **ffi.set_unicode(enabled_flag)**: Windows: if ``enabled_flag`` is
214 True, enable the ``UNICODE`` and ``_UNICODE`` defines in C, and
215 declare the types ``TBYTE TCHAR LPCTSTR PCTSTR LPTSTR PTSTR PTBYTE
216 PTCHAR`` to be (pointers to) ``wchar_t``. If ``enabled_flag`` is
217 False, declare these types to be (pointers to) plain 8-bit characters.
218 (These types are not predeclared at all if you don't call
219 ``set_unicode()``.)
220
221 The reason behind this method is that a lot of standard functions have
222 two versions, like ``MessageBoxA()`` and ``MessageBoxW()``. The
223 official interface is ``MessageBox()`` with arguments like
224 ``LPTCSTR``. Depending on whether ``UNICODE`` is defined or not, the
225 standard header renames the generic function name to one of the two
226 specialized versions, and declares the correct (unicode or not) types.
227
228 Usually, the right thing to do is to call this method with True. Be
229 aware (particularly on Python 2) that, afterwards, you need to pass unicode
230 strings as arguments instead of byte strings.
231
232
233 .. _loading-libraries:
234 .. _dlopen:
235
236 ffi.dlopen(): loading libraries in ABI mode
237 -------------------------------------------
238
239 ``ffi.dlopen(libpath, [flags])``: this function opens a shared library and
240 returns a module-like library object. Use this when you are fine with
241 the limitations of ABI-level access to the system (dependency on ABI
242 details, getting crashes instead of C compiler errors/warnings, and
243 higher overhead to call the C functions). In case of doubt, read again
244 `ABI versus API`_ in the overview.
245
246 .. _`ABI versus API`: overview.html#abi-versus-api
247
248 You can use the library object to call the functions previously
249 declared by ``ffi.cdef()``, to read constants, and to read or write
250 global variables. Note that you can use a single ``cdef()`` to
251 declare functions from multiple libraries, as long as you load each of
252 them with ``dlopen()`` and access the functions from the correct one.
253
254 The ``libpath`` is the file name of the shared library, which can
255 contain a full path or not (in which case it is searched in standard
256 locations, as described in ``man dlopen``), with extensions or not.
257 Alternatively, if ``libpath`` is None, it returns the standard C library
258 (which can be used to access the functions of glibc, on Linux). Note
259 that ``libpath`` `cannot be None`__ on Windows with Python 3.
260
261 .. __: http://bugs.python.org/issue23606
262
263 Let me state it again: this gives ABI-level access to the library, so
264 you need to have all types declared manually exactly as they were
265 while the library was made. No checking is done. Mismatches can
266 cause random crashes. API-level access, on the other hand, is safer.
267 Speed-wise, API-level access is much faster (it is common to have
268 the opposite misconception about performance).
269
270 Note that only functions and global variables live in library objects;
271 the types exist in the ``ffi`` instance independently of library objects.
272 This is due to the C model: the types you declare in C are not tied to a
273 particular library, as long as you ``#include`` their headers; but you
274 cannot call functions from a library without linking it in your program,
275 as ``dlopen()`` does dynamically in C.
276
277 For the optional ``flags`` argument, see ``man dlopen`` (ignored on
278 Windows). It defaults to ``ffi.RTLD_NOW``.
279
280 This function returns a "library" object that gets closed when it goes
281 out of scope. Make sure you keep the library object around as long as
282 needed. (Alternatively, the out-of-line FFIs have a method
283 ``ffi.dlclose(lib)``.)
284
285 .. _dlopen-note:
286
287 Note: the old version of ``ffi.dlopen()`` from the in-line ABI mode
288 tries to use ``ctypes.util.find_library()`` if it cannot directly find
289 the library. The newer out-of-line ``ffi.dlopen()`` no longer does it
290 automatically; it simply passes the argument it receives to the
291 underlying ``dlopen()`` or ``LoadLibrary()`` function. If needed, it
292 is up to you to use ``ctypes.util.find_library()`` or any other way to
293 look for the library's filename. This also means that
294 ``ffi.dlopen(None)`` no longer work on Windows; try instead
295 ``ffi.dlopen(ctypes.util.find_library('c'))``.
296
297 *New in version 1.14:* ``ffi.dlopen(handle)``: instead of a file path,
298 you can give an already-opened library handle, as a cdata of type
299 ``void *``. Such a call converts this handle into a regular FFI object
300 with the functions and global variables declared by ``ffi.cdef()``.
301 Useful if you have special needs (e.g. you need the GNU extension
302 ``dlmopen()``, which you can itself declare and call using a different
303 ``ffi`` object). Note that in this variant, ``dlclose()`` is not called
304 automatically if the FFI object is garbage-collected (but you can still
305 call ``ffi.dlclose()`` explicitly if needed).
306
307 *New in version 1.17:* on Windows, ``ffi.dlopen(filename, flags=0)`` now
308 passes the flags to ``LoadLibraryEx()``. Moreover, if you use the
309 default value of 0 but ``filename`` contains a slash or backslash
310 character, it will instead use
311 ``LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR``.
312 This ensures that dependent DLLs from the same path are also found.
313 It is what ctypes does too.
314
315
316 .. _set_source:
317
318 ffibuilder.set_source(): preparing out-of-line modules
319 ------------------------------------------------------
320
321 **ffibuilder.set_source(module_name, c_header_source, [\*\*keywords...])**:
322 prepare the ffi for producing out-of-line an external module called
323 ``module_name``.
324
325 ``ffibuilder.set_source()`` by itself does not write any file, but merely
326 records its arguments for later. It can therefore be called before or
327 after ``ffibuilder.cdef()``.
328
329 In **ABI mode,** you call ``ffibuilder.set_source(module_name, None)``. The
330 argument is the name (or dotted name inside a package) of the Python
331 module to generate. In this mode, no C compiler is called.
332
333 In **API mode,** the ``c_header_source`` argument is a string that
334 will be pasted into the .c file generated. Typically, it is specified as
335 ``r""" ...multiple lines of C code... """`` (the ``r`` prefix allows these
336 lines to contain a literal ``\n``, for example). This piece of C code
337 typically contains some ``#include``, but may also contain more,
338 like definitions for custom "wrapper" C functions. The goal is that
339 the .c file can be generated like this::
340
341 // C file "module_name.c"
342 #include <Python.h>
343
344 ...c_header_source...
345
346 ...magic code...
347
348 where the "magic code" is automatically generated from the ``cdef()``.
349 For example, if the ``cdef()`` contains ``int foo(int x);`` then the
350 magic code will contain logic to call the function ``foo()`` with an
351 integer argument, itself wrapped inside some CPython or PyPy-specific
352 code.
353
354 The keywords arguments to ``set_source()`` control how the C compiler
355 will be called. They are passed directly to distutils_ or setuptools_
356 and include at least ``sources``, ``include_dirs``, ``define_macros``,
357 ``undef_macros``, ``libraries``, ``library_dirs``, ``extra_objects``,
358 ``extra_compile_args`` and ``extra_link_args``. You typically need at
359 least ``libraries=['foo']`` in order to link with ``libfoo.so`` or
360 ``libfoo.so.X.Y``, or ``foo.dll`` on Windows. The ``sources`` is a
361 list of extra .c files compiled and linked together (the file
362 ``module_name.c`` shown above is always generated and automatically added as the
363 first argument to ``sources``). See the distutils documentation for
364 `more information about the other arguments`__.
365
366 .. __: https://setuptools.pypa.io/en/stable/userguide/ext_modules.html#building-extension-modules
367 .. _distutils: http://docs.python.org/3.11/distutils/setupscript.html#describing-extension-modules
368 .. _setuptools: https://setuptools.pypa.io/
369
370 An extra keyword argument processed internally is
371 ``source_extension``, defaulting to ``".c"``. The file generated will
372 be actually called ``module_name + source_extension``. Example for
373 C++ (but note that there are still a few known issues of C-versus-C++
374 compatibility):
375
376 .. code-block:: python
377
378 ffibuilder.set_source("mymodule", r'''
379 extern "C" {
380 int somefunc(int somearg) { return real_cpp_func(somearg); }
381 }
382 ''', source_extension='.cpp')
383
384 .. _pkgconfig:
385
386 **ffibuilder.set_source_pkgconfig(module_name, pkgconfig_libs,
387 c_header_source, [\*\*keywords...])**:
388
389 *New in version 1.12.* This is equivalent to ``set_source()`` but it
390 first calls the system utility ``pkg-config`` with the package names
391 given in the list ``pkgconfig_libs``. It collects the information
392 obtained in this way and adds it to the explicitly-provided
393 ``**keywords`` (if any). This should probably not be used on Windows.
394
395 If the ``pkg-config`` program is not installed or does not know about
396 the requested library, the call fails with ``cffi.PkgConfigError``. If
397 necessary, you can catch this error and try to call ``set_source()``
398 directly. (Ideally, you should also do that if the ``ffibuilder``
399 instance has no method ``set_source_pkgconfig()``, to support older
400 versions of cffi.)
401
402
403 Letting the C compiler fill the gaps
404 ------------------------------------
405
406 If you are using a C compiler ("API mode"), then:
407
408 * functions taking or returning integer or floating-point arguments can be
409 misdeclared: if e.g. a function is declared by ``cdef()`` as taking a
410 ``int``, but actually takes a ``long``, then the C compiler handles the
411 difference.
412
413 * other arguments are checked: you get a compilation warning or error
414 if you pass a ``int *`` argument to a function expecting a ``long *``.
415
416 * similarly, most other things declared in the ``cdef()`` are checked,
417 to the best we implemented so far; mistakes give compilation
418 warnings or errors.
419
420 Moreover, you can use "``...``" (literally, dot-dot-dot) in the
421 ``cdef()`` at various places, in order to ask the C compiler to fill
422 in the details. These places are:
423
424 ``struct { }`` or ``union { }``
425 Use "``...;``" as the last "field" to declare a partial structure.
426 This means fields can be left undeclared, declared out of order, or use
427 non-standard alignment. Precisely, the field offsets, total struct size,
428 and total struct alignment aren't deduced by looking at the ``cdef``.
429 Instead they will be corrected by the compiler. Note that you can only
430 access fields that you declared; and you must use the correct type for
431 those you declare, the compiler can't figure it out. Any ``struct``
432 declaration which doesn't use "``...``" is assumed to be exact, but this is
433 checked: you get an error if it is not correct.
434
435 ``typedef int... foo_t;``
436 Declares the type ``foo_t`` as an integer type
437 whose exact size and signedness is not specified. The compiler will
438 figure it out. (Note that this requires ``set_source()``; it does
439 not work with ``verify()``.) The ``int...`` can be replaced with
440 ``long...`` or ``unsigned long long...`` or any other primitive
441 integer type, with no effect. The type will always map to one of
442 ``(u)int(8,16,32,64)_t`` in Python, but in the generated C code,
443 only ``foo_t`` is used.
444
445 ``typedef float... foo_t;``
446 *New in version 1.3:* Declares ``foo_t`` as a-float-or-a-double; the
447 compiler will figure out which it is. ``typedef double... foo_t;`` has
448 the same effect. Note that if the actual C type is even larger
449 (``long double`` on some platforms), then compilation will fail.
450 The problem is that the Python "float" type cannot be used to store
451 the extra precision. (Use the non-dot-dot-dot syntax ``typedef long
452 double foo_t;`` as usual, which returns values that are not Python
453 floats at all but cdata "long double" objects.)
454
455 ``typedef ... foo_t;``
456 Declares the type
457 ``foo_t`` as opaque. Useful mainly for when the API takes and returns
458 ``foo_t *`` without you needing to look inside the ``foo_t``. Also
459 works with "``typedef ... *foo_p;``" which declares the pointer type
460 ``foo_p`` without giving a name to the opaque type itself. Note that
461 such an opaque struct has no known size, which prevents some operations
462 from working (mostly like in C). *You cannot use this syntax to
463 declare a specific type, like an integer type! It declares opaque
464 struct-like types only.* In some cases you need to say that
465 ``foo_t`` is not opaque, but just a struct where you don't know any
466 field; then you would use "``typedef struct { ...; } foo_t;``".
467
468 ``extern int n[...];``
469 When used as structure fields or in global variables,
470 arrays can have an unspecified length. The
471 length is completed by the C compiler.
472 This is slightly different from "``extern int n[];``", because the latter
473 means that the length is not known even to the C compiler, and thus
474 no attempt is made to complete it. This supports
475 multidimensional arrays: "``extern int n[...][...];``".
476
477 *New in version 1.2:* "``extern int m[][...];``", i.e. ``...`` can be used
478 in the innermost dimensions without being also used in the outermost
479 dimension. In the example given, the length of the ``m`` array is
480 assumed not to be known to the C compiler, but the length of every
481 item (like the sub-array ``m[0]``) is always known the C compiler.
482 In other words, only the outermost dimension can be specified as
483 ``[]``, both in C and in CFFI, but any dimension can be given as
484 ``[...]`` in CFFI.
485
486 ``enum foo { A, B, C, ... };``
487 If you don't know the exact order (or values) of the declared
488 constants, then declare them with a trailing "``...``".
489 The C compiler will be used to figure
490 out the exact values of the constants. An alternative syntax is
491 "``enum foo { A=..., B, C };``" or even
492 "``enum foo { A=..., B=..., C=... };``". Like
493 with structs, an ``enum`` without "``...``" is assumed to
494 be exact, and this is checked.
495
496 ``#define FOO ...``
497 For integer constants and macros you can write a line in the ``cdef``
498 with any macro name FOO but with ``...`` as a value. Provided the macro
499 is defined to be an integer value, this value will be available via
500 an attribute of the library object. The
501 same effect can be achieved by writing a declaration
502 ``static const int FOO;``. The latter is more general because it
503 supports other types than integer types (note: the C syntax is then
504 to write the ``const`` together with the variable name, as in
505 ``static char *const FOO;``).
506
507 Currently, it is not supported to find automatically which of the
508 various integer or float types you need at which place---except in the
509 following case: if such a type is explicitly named. For an integer
510 type, use ``typedef int... the_type_name;``, or another type like
511 ``typedef unsigned long... the_type_name;``. Both are equivalent and
512 replaced by the real C type, which must be an integer type.
513 Similarly, for floating-point types, use ``typedef float...
514 the_type_name;`` or equivalently ``typedef double... the_type_name;``.
515 Note that ``long double`` cannot be detected this way.
516
517 In the case of function arguments or return types, when it is a simple
518 integer/float type, you can simply misdeclare it. If you misdeclare a
519 function ``void f(long)`` as ``void f(int)``, it still works (but you
520 have to call it with arguments that fit an int). It works because the C
521 compiler will do the casting for us. This C-level casting of arguments
522 and return types only works for regular function, and not for function
523 pointer types; currently, it also does not work for variadic functions.
524
525 For more complex types, you have no choice but be precise. For example,
526 you cannot misdeclare a ``int *`` argument as ``long *``, or a global
527 array ``extern int a[5];`` as ``extern long a[5];``. CFFI considers `all types listed
528 above`_ as primitive (so ``extern long long a[5];`` and ``extern int64_t a[5]`` are
529 different declarations). The reason for that is detailed in `a comment
530 about an issue.`__
531
532 .. __: https://foss.heptapod.net/pypy/cffi/-/issues/265#note_50393
533
534
535 ffibuilder.compile() etc.: compiling out-of-line modules
536 --------------------------------------------------------
537
538 You can use one of the following functions to actually generate the
539 .py or .c file prepared with ``ffibuilder.set_source()`` and
540 ``ffibuilder.cdef()``.
541
542 Note that these function won't overwrite a .py/.c file with exactly
543 the same content, to preserve the mtime. In some cases where you need
544 the mtime to be updated anyway, delete the file before calling the
545 functions.
546
547 *New in version 1.8:* the C code produced by ``emit_c_code()`` or
548 ``compile()`` contains ``#define Py_LIMITED_API``. This means that on
549 CPython >= 3.2, compiling this source produces a binary .so/.dll that
550 should work for any version of CPython >= 3.2 (as opposed to only for
551 the same version of CPython x.y). However, the standard ``distutils``
552 package will still produce a file called e.g.
553 ``NAME.cpython-35m-x86_64-linux-gnu.so``. You can manually rename it to
554 ``NAME.abi3.so``, or use setuptools version 26 or later. Also, note
555 that compiling with a debug version of Python will not actually define
556 ``Py_LIMITED_API``, as doing so makes ``Python.h`` unhappy.
557
558 *New in version 1.12:* ``Py_LIMITED_API`` is now defined on Windows too.
559 If you use ``virtualenv``, you need a recent version of it: versions
560 older than 16.0.0 forgot to copy ``python3.dll`` into the virtual
561 environment. In case upgrading ``virtualenv`` is a real problem, you
562 can manually edit the C code to remove the first line ``# define
563 Py_LIMITED_API``.
564
565 **ffibuilder.compile(tmpdir='.', verbose=False, debug=None):**
566 explicitly generate the .py or .c file,
567 and (if .c) compile it. The output file is (or are) put in the
568 directory given by ``tmpdir``. In the examples given here, we use
569 ``if __name__ == "__main__": ffibuilder.compile()`` in the build scripts---if
570 they are directly executed, this makes them rebuild the .py/.c file in
571 the current directory. (Note: if a package is specified in the call
572 to ``set_source()``, then a corresponding subdirectory of the ``tmpdir``
573 is used.)
574
575 *New in version 1.4:* ``verbose`` argument. If True, it prints the
576 usual distutils output, including the command lines that call the
577 compiler. (This parameter might be changed to True by default in a
578 future release.)
579
580 *New in version 1.8.1:* ``debug`` argument. If set to a bool, it
581 controls whether the C code is compiled in debug mode or not. The
582 default None means to use the host Python's ``sys.flags.debug``.
583 Starting with version 1.8.1, if you are running a debug-mode Python, the
584 C code is thus compiled in debug mode by default (note that it is anyway
585 necessary to do so on Windows).
586
587 **ffibuilder.emit_python_code(filename):** generate the given .py file (same
588 as ``ffibuilder.compile()`` for ABI mode, with an explicitly-named file to
589 write). If you choose, you can include this .py file pre-packaged in
590 your own distributions: it is identical for any Python version (2 or
591 3).
592
593 *New in version 1.17.1:* ``filename`` can instead be a file-like object
594 (such as a StringIO instance). The generated code will be written to this
595 file-like object. However, if an error arises during generation, partial
596 code may be written; it is the caller's responsibility to clean up
597 if this occurs.
598
599 **ffibuilder.emit_c_code(filename):** generate the given .c file (for API
600 mode) without compiling it. Can be used if you have some other method
601 to compile it, e.g. if you want to integrate with some larger build
602 system that will compile this file for you. You can also distribute
603 the .c file: unless the build script you used depends on the OS or
604 platform, the .c file itself is generic (it would be exactly the same
605 if produced on a different OS, with a different version of CPython, or
606 with PyPy; it is done with generating the appropriate ``#ifdef``).
607
608 *New in version 1.17.1:* ``filename`` can instead be a file-like object
609 (such as a StringIO instance). The generated code will be written to this
610 file-like object. However, if an error arises during generation, partial
611 code may be written; it is the caller's responsibility to clean up
612 if this occurs.
613
614 **ffibuilder.distutils_extension(tmpdir='build', verbose=True):** for
615 distutils-based ``setup.py`` files. Calling this creates the .c file
616 if needed in the given ``tmpdir``, and returns a
617 ``distutils.core.Extension`` instance.
618
619 For Setuptools, you use instead the line
620 ``cffi_modules=["path/to/foo_build.py:ffibuilder"]`` in ``setup.py``. This
621 line asks Setuptools to import and use a helper provided by CFFI,
622 which in turn executes the file ``path/to/foo_build.py`` (as with
623 ``execfile()``) and looks up its global variable called ``ffibuilder``. You
624 can also say ``cffi_modules=["path/to/foo_build.py:maker"]``, where
625 ``maker`` names a global function; it is called with no argument and
626 is supposed to return a ``FFI`` object.
627
628
629 ffi/ffibuilder.include(): combining multiple CFFI interfaces
630 ------------------------------------------------------------
631
632 **ffi/ffibuilder.include(other_ffi)**: includes the typedefs, structs, unions,
633 enums and constants defined in another FFI instance. This is meant
634 for large projects where one CFFI-based interface depends on some
635 types declared in a different CFFI-based interface.
636
637 *Note that you should only use one ffi object per library; the intended
638 usage of ffi.include() is if you want to interface with several
639 inter-dependent libraries.* For only one library, make one ``ffi``
640 object. (You can write several ``cdef()`` calls over the same ``ffi``
641 from several Python files, if one file would be too large.)
642
643 For out-of-line modules, the ``ffibuilder.include(other_ffibuilder)``
644 line should
645 occur in the build script, and the ``other_ffibuilder`` argument should be
646 another FFI instance that comes from another build script. When the two build
647 scripts are turned into generated files, say ``_ffi.so`` and
648 ``_other_ffi.so``, then importing ``_ffi.so`` will internally cause
649 ``_other_ffi.so`` to be imported. At that point, the real
650 declarations from ``_other_ffi.so`` are combined with the real
651 declarations from ``_ffi.so``.
652
653 The usage of ``ffi.include()`` is the cdef-level equivalent of a
654 ``#include`` in C, where a part of the program might include types and
655 functions defined in another part for its own usage. You can see on
656 the ``ffi`` object (and associated ``lib`` objects on the *including*
657 side) the types and constants declared on the included side. In API
658 mode, you can also see the functions and global variables directly.
659 In ABI mode, these must be accessed via the original ``other_lib``
660 object returned by the ``dlopen()`` method on ``other_ffi``.
661
662
663 ffi.cdef() limitations
664 ----------------------
665
666 All of the ANSI C *declarations* should be supported in ``cdef()``,
667 and some of C99. (This excludes any ``#include`` or ``#ifdef``.)
668 Known missing features that are either in C99, or are GCC or MSVC
669 extensions:
670
671 * Any ``__attribute__`` or ``#pragma pack(n)``
672
673 * Additional types: special-size floating and fixed
674 point types, vector types, and so on.
675
676 * The C99 types ``float _Complex`` and ``double _Complex`` are supported
677 by cffi since version 1.11, but not libffi: you cannot call C
678 functions with complex arguments or return value, except if they are
679 directly API-mode functions. The type ``long double _Complex`` is not
680 supported at all (declare and use it as if it were an array of two
681 ``long double``, and write wrapper functions in C with set_source()).
682
683 * ``__restrict__`` or ``__restrict`` are extensions of, respectively,
684 GCC and MSVC. They are not recognized. But ``restrict`` is a C
685 keyword and is accepted (and ignored).
686
687 Note that declarations like ``int field[];`` in
688 structures are interpreted as variable-length structures. Declarations
689 like ``int field[...];`` on the other hand are arrays whose length is
690 going to be completed by the compiler. You can use ``int field[];``
691 for array fields that are not, in fact, variable-length; it works too,
692 but in this case, as CFFI
693 believes it cannot ask the C compiler for the length of the array, you
694 get reduced safety checks: for example, you risk overwriting the
695 following fields by passing too many array items in the constructor.
696
697 *New in version 1.2:*
698 Thread-local variables (``__thread``) can be accessed, as well as
699 variables defined as dynamic macros (``#define myvar (*fetchme())``).
700 Before version 1.2, you need to write getter/setter functions.
701
702 Note that if you declare a variable in ``cdef()`` without using
703 ``const``, CFFI assumes it is a read-write variable and generates two
704 pieces of code, one to read it and one to write it. If the variable
705 cannot in fact be written to in C code, for one reason or another, it
706 will not compile. In this case, you can declare it as a constant: for
707 example, instead of ``foo_t *myglob;`` you would use ``foo_t *const
708 myglob;``. Note also that ``const foo_t *myglob;`` is a *variable;* it
709 contains a variable pointer to a constant ``foo_t``.
710
711
712 Debugging dlopen'ed C libraries
713 -------------------------------
714
715 A few C libraries are actually hard to use correctly in a ``dlopen()``
716 setting. This is because most C libraries are intended for, and tested
717 with, a situation where they are *linked* with another program, using
718 either static linking or dynamic linking --- but from a program written
719 in C, at start-up, using the linker's capabilities instead of
720 ``dlopen()``.
721
722 This can occasionally create issues. You would have the same issues in
723 another setting than CFFI, like with ``ctypes`` or even plain C code that
724 calls ``dlopen()``. This section contains a few generally useful
725 environment variables (on Linux) that can help when debugging these
726 issues.
727
728 **export LD_TRACE_LOADED_OBJECTS=all**
729
730 provides a lot of information, sometimes too much depending on the
731 setting. Output verbose debugging information about the dynamic
732 linker. If set to ``all`` prints all debugging information it has, if
733 set to ``help`` prints a help message about which categories can be
734 specified in this environment variable
735
736 **export LD_VERBOSE=1**
737
738 (glibc since 2.1) If set to a nonempty string, output symbol
739 versioning information about the program if querying information
740 about the program (i.e., either ``LD_TRACE_LOADED_OBJECTS`` has been set,
741 or ``--list`` or ``--verify`` options have been given to the dynamic
742 linker).
743
744 **export LD_WARN=1**
745
746 (ELF only)(glibc since 2.1.3) If set to a nonempty string, warn
747 about unresolved symbols.
748
749
750 ffi.verify(): in-line API-mode
751 ------------------------------
752
753 **ffi.verify()** is supported for backward compatibility, but is
754 deprecated. ``ffi.verify(c_header_source, tmpdir=.., ext_package=..,
755 modulename=.., flags=.., **kwargs)`` makes and compiles a C file from
756 the ``ffi.cdef()``, like ``ffi.set_source()`` in API mode, and then
757 immediately loads and returns the dynamic library object. Some
758 non-trivial logic is used to decide if the dynamic library must be
759 recompiled or not; see below for ways to control it.
760
761 The ``c_header_source`` and the extra keyword arguments have the
762 same meaning as in ``ffi.set_source()``.
763
764 One remaining use case for ``ffi.verify()`` would be the following
765 hack to find explicitly the size of any type, in bytes, and have it
766 available in Python immediately (e.g. because it is needed in order to
767 write the rest of the build script):
768
769 .. code-block:: python
770
771 ffi = cffi.FFI()
772 ffi.cdef("const int mysize;")
773 lib = ffi.verify("const int mysize = sizeof(THE_TYPE);")
774 print lib.mysize
775
776 Extra arguments to ``ffi.verify()``:
777
778 * ``tmpdir`` controls where the C
779 files are created and compiled. Unless the ``CFFI_TMPDIR`` environment
780 variable is set, the default is
781 ``directory_containing_the_py_file/__pycache__`` using the
782 directory name of the .py file that contains the actual call to
783 ``ffi.verify()``. (This is a bit of a hack but is generally
784 consistent with the location of the .pyc files for your library.
785 The name ``__pycache__`` itself comes from Python 3.)
786
787 * ``ext_package`` controls in which package the
788 compiled extension module should be looked from. This is
789 only useful after distributing ffi.verify()-based modules.
790
791 * The ``tag`` argument gives an extra string inserted in the
792 middle of the extension module's name: ``_cffi_<tag>_<hash>``.
793 Useful to give a bit more context, e.g. when debugging.
794
795 * The ``modulename`` argument can be used to force a specific module
796 name, overriding the name ``_cffi_<tag>_<hash>``. Use with care,
797 e.g. if you are passing variable information to ``verify()`` but
798 still want the module name to be always the same (e.g. absolute
799 paths to local files). In this case, no hash is computed and if
800 the module name already exists it will be reused without further
801 check. Be sure to have other means of clearing the ``tmpdir``
802 whenever you change your sources.
803
804 * ``source_extension`` has the same meaning as in ``ffibuilder.set_source()``.
805
806 * The optional ``flags`` argument (ignored on Windows) defaults to
807 ``ffi.RTLD_NOW``; see ``man dlopen``. (With
808 ``ffibuilder.set_source()``, you would use ``sys.setdlopenflags()``.)
809
810 * The optional ``relative_to`` argument is useful if you need to list
811 local files passed to the C compiler::
812
813 ext = ffi.verify(..., sources=['foo.c'], relative_to=__file__)
814
815 The line above is roughly the same as::
816
817 ext = ffi.verify(..., sources=['/path/to/this/file/foo.c'])
818
819 except that the default name of the produced library is built from
820 the CRC checksum of the argument ``sources``, as well as most other
821 arguments you give to ``ffi.verify()`` -- but not ``relative_to``.
822 So if you used the second line, it would stop finding the
823 already-compiled library after your project is installed, because
824 the ``'/path/to/this/file'`` suddenly changed. The first line does
825 not have this problem.
826
827 Note that during development, every time you change the C sources that
828 you pass to ``cdef()`` or ``verify()``, then the latter will create a
829 new module file name, based on two CRC32 hashes computed from these
830 strings. This creates more and more files in the ``__pycache__``
831 directory. It is recommended that you clean it up from time to time.
832 A nice way to do that is to add, in your test suite, a call to
833 ``cffi.verifier.cleanup_tmpdir()``. Alternatively, you can manually
834 remove the whole ``__pycache__`` directory.
835
836 An alternative cache directory can be given as the ``tmpdir`` argument
837 to ``verify()``, via the environment variable ``CFFI_TMPDIR``, or by
838 calling ``cffi.verifier.set_tmpdir(path)`` prior to calling
839 ``verify``.
840
841
842 Upgrading from CFFI 0.9 to CFFI 1.0
843 -----------------------------------
844
845 CFFI 1.0 is backward-compatible, but it is still a good idea to
846 consider moving to the out-of-line approach new in 1.0. Here are the
847 steps.
848
849 **ABI mode** if your CFFI project uses ``ffi.dlopen()``:
850
851 .. code-block:: python
852
853 import cffi
854
855 ffi = cffi.FFI()
856 ffi.cdef("stuff")
857 lib = ffi.dlopen("libpath")
858
859 and *if* the "stuff" part is big enough that import time is a concern,
860 then rewrite it as described in `the out-of-line but still ABI mode`__
861 above. Optionally, see also the :ref:`C source generation <cffi_gen_src_docs>`
862 documentation.
863
864 .. __: out-of-line-abi_
865
866
867 **API mode** if your CFFI project uses ``ffi.verify()``:
868
869 .. code-block:: python
870
871 import cffi
872
873 ffi = cffi.FFI()
874 ffi.cdef("stuff")
875 lib = ffi.verify("real C code")
876
877 then you should really rewrite it as described in `the out-of-line, API
878 mode`__ above. It avoids a number of issues that have caused
879 ``ffi.verify()`` to grow a number of extra arguments over time. Then
880 see the :ref:`C source generation <cffi_gen_src_docs>`
881 documentation. Also, remember to remove the ``ext_package=".."`` from
882 your ``setup.py``, which was sometimes needed with ``verify()`` but is
883 just creating confusion with ``set_source()``.
884
885 .. __: out-of-line-api_
886
887 The following example should work both with old (pre-1.0) and new
888 versions of CFFI---supporting both is important to run on old
889 versions of PyPy (CFFI 1.0 does not work in PyPy < 2.6):
890
891 .. code-block:: python
892
893 # in a separate file "package/foo_build.py"
894 import cffi
895
896 ffi = cffi.FFI()
897 C_HEADER_SRC = r'''
898 #include "somelib.h"
899 '''
900 C_KEYWORDS = dict(libraries=['somelib'])
901
902 if hasattr(ffi, 'set_source'):
903 ffi.set_source("package._foo", C_HEADER_SRC, **C_KEYWORDS)
904
905 ffi.cdef('''
906 int foo(int);
907 ''')
908
909 if __name__ == "__main__":
910 ffi.compile()
911
912 And in the main program:
913
914 .. code-block:: python
915
916 try:
917 from package._foo import ffi, lib
918 except ImportError:
919 from package.foo_build import ffi, C_HEADER_SRC, C_KEYWORDS
920 lib = ffi.verify(C_HEADER_SRC, **C_KEYWORDS)
921
922 (FWIW, this latest trick can be used more generally to allow the
923 import to "work" even if the ``_foo`` module was not generated.)
924
925 Writing a ``setup.py`` script that works both with CFFI 0.9 and 1.0
926 requires explicitly checking the version of CFFI that we can have---it
927 is hard-coded as a built-in module in PyPy:
928
929 .. code-block:: python
930
931 if '_cffi_backend' in sys.builtin_module_names: # PyPy
932 import _cffi_backend
933 requires_cffi = "cffi==" + _cffi_backend.__version__
934 else:
935 requires_cffi = "cffi>=1.0.0"
936
937 Then we use the ``requires_cffi`` variable to give different arguments to
938 ``setup()`` as needed, e.g.:
939
940 .. code-block:: python
941
942 if requires_cffi.startswith("cffi==0."):
943 # backward compatibility: we have "cffi==0.*"
944 from package.foo_build import ffi
945 extra_args = dict(
946 ext_modules=[ffi.verifier.get_extension()],
947 ext_package="...", # if needed
948 )
949 else:
950 extra_args = dict(
951 setup_requires=[requires_cffi],
952 cffi_modules=['package/foo_build.py:ffi'],
953 )
954 setup(
955 name=...,
956 ...,
957 install_requires=[requires_cffi],
958 **extra_args
959 )