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