1======================================================= 2Overview 3======================================================= 4 5.. contents:: 6 7 8The first section presents a simple working 9example of using CFFI to call a C function in a compiled shared object 10(DLL) from Python. CFFI is 11flexible and covers several other use cases presented in the second 12section. The third section shows how to export Python functions 13to a Python interpreter embedded in a C or C++ application. The last 14two sections delve deeper in the CFFI library. 15 16Make sure you have `cffi installed`__. 17 18.. __: installation.html 19 20.. _out-of-line-api-level: 21.. _real-example: 22 23 24Main mode of usage 25------------------ 26 27The main way to use CFFI is as an interface to some already-compiled 28shared object which is provided by other means. Imagine that you have a 29system-installed shared object called ``piapprox.dll`` (Windows) or 30``libpiapprox.so`` (Linux and others) or ``libpiapprox.dylib`` (OS X), 31exporting a function ``float pi_approx(int n);`` that computes some 32approximation of pi given a number of iterations. You want to call 33this function from Python. Note this method works equally well with a 34static library ``piapprox.lib`` (Windows) or ``libpiapprox.a``. 35 36Create the file ``piapprox_build.py``: 37 38.. code-block:: python 39 40 from cffi import FFI 41 ffibuilder = FFI() 42 43 # cdef() expects a single string declaring the C types, functions and 44 # globals needed to use the shared object. It must be in valid C syntax. 45 ffibuilder.cdef(""" 46 float pi_approx(int n); 47 """) 48 49 # set_source() gives the name of the python extension module to 50 # produce, and some C source code as a string. This C code needs 51 # to make the declarated functions, types and globals available, 52 # so it is often just the "#include". 53 ffibuilder.set_source("_pi_cffi", 54 """ 55 #include "pi.h" // the C header of the library 56 """, 57 libraries=['piapprox']) # library name, for the linker 58 59 if __name__ == "__main__": 60 ffibuilder.compile(verbose=True) 61 62Execute this script. If everything is OK, it should produce 63``_pi_cffi.c``, and then invoke the compiler on it. The produced 64``_pi_cffi.c`` contains a copy of the string given in :ref:`set_source() <set_source>`, 65in this example the ``#include "pi.h"``. Afterwards, it contains glue code 66for all the functions, types and globals declared in the :ref:`cdef() <cdef>` above. 67 68At runtime, you use the extension module like this: 69 70.. code-block:: python 71 72 from _pi_cffi import ffi, lib 73 print(lib.pi_approx(5000)) 74 75That's all! In the rest of this page, we describe some more advanced 76examples and other CFFI modes. In particular, there is a complete 77example `if you don't have an already-installed C library to call`_. 78 79For more information about the ``cdef()`` and ``set_source()`` methods 80of the ``FFI`` class, see `Preparing and Distributing modules`__. 81 82.. __: cdef.html 83 84When your example works, a common alternative to running the build 85script manually is to have it run as part of a ``setup.py``. Here is 86an example using the Setuptools distribution: 87 88.. code-block:: python 89 90 from setuptools import setup 91 92 setup( 93 ... 94 setup_requires=["cffi>=1.0.0"], 95 cffi_modules=["piapprox_build:ffibuilder"], # "filename:global" 96 install_requires=["cffi>=1.0.0"], 97 ) 98 99 100Other CFFI modes 101---------------- 102 103CFFI can be used in one of four modes: "ABI" versus "API" level, 104each with "in-line" or "out-of-line" preparation (or compilation). 105 106The **ABI mode** accesses libraries at the binary level, whereas the 107faster **API mode** accesses them with a C compiler. We explain the 108difference in more details below__. 109 110.. __: `abi-versus-api`_ 111 112In the **in-line mode,** everything is set up every time you import 113your Python code. In the **out-of-line mode,** you have a separate 114step of preparation (and possibly C compilation) that produces a 115module which your main program can then import. 116 117 118Simple example (ABI level, in-line) 119+++++++++++++++++++++++++++++++++++ 120 121May look familiar to those who have used ctypes_. 122 123.. code-block:: python 124 125 >>> from cffi import FFI 126 >>> ffi = FFI() 127 >>> ffi.cdef(""" 128 ... int printf(const char *format, ...); // copy-pasted from the man page 129 ... """) 130 >>> C = ffi.dlopen(None) # loads the entire C namespace 131 >>> arg = ffi.new("char[]", b"world") # equivalent to C code: char arg[] = "world"; 132 >>> C.printf(b"hi there, %s.\n", arg) # call printf 133 hi there, world. 134 17 # this is the return value 135 >>> 136 137Note that ``char *`` arguments expect a ``bytes`` object. If you have a 138``str`` (or a ``unicode`` on Python 2) you need to encode it explicitly 139with ``somestring.encode(myencoding)``. 140 141*Python 3 on Windows:* :ref:`ffi.dlopen(None) <dlopen>` does not work. This problem 142is messy and not really fixable. The problem does not occur if you try 143to call a function from a specific DLL that exists on your system: then 144you use ``ffi.dlopen("path.dll")``. 145 146*This example does not call any C compiler. It works in the so-called 147ABI mode, which means that it will crash if you call some function or 148access some fields of a structure that was slightly misdeclared in the 149cdef().* 150 151If using a C compiler to install your module is an option, it is highly 152recommended to use the API mode instead. (It is also faster.) 153 154 155Struct/Array Example (minimal, in-line) 156+++++++++++++++++++++++++++++++++++++++ 157 158.. code-block:: python 159 160 from cffi import FFI 161 ffi = FFI() 162 ffi.cdef(""" 163 typedef struct { 164 unsigned char r, g, b; 165 } pixel_t; 166 """) 167 image = ffi.new("pixel_t[]", 800*600) 168 169 f = open('data', 'rb') # binary mode -- important 170 f.readinto(ffi.buffer(image)) 171 f.close() 172 173 image[100].r = 255 174 image[100].g = 192 175 image[100].b = 128 176 177 f = open('data', 'wb') 178 f.write(ffi.buffer(image)) 179 f.close() 180 181This can be used as a more flexible replacement of the struct_ and 182array_ modules, and replaces ctypes_. You could also call :ref:`ffi.new("pixel_t[600][800]") <new>` 183and get a two-dimensional array. 184 185.. _struct: http://docs.python.org/library/struct.html 186.. _array: http://docs.python.org/library/array.html 187.. _ctypes: http://docs.python.org/library/ctypes.html 188 189*This example does not call any C compiler.* 190 191This example also admits an out-of-line equivalent. It is similar to 192the first example `Main mode of usage`_ above, 193but passing ``None`` as the second argument to 194:ref:`ffibuilder.set_source() <set_source>`. Then in the main program you write 195``from _simple_example import ffi`` and then the same content as the 196in-line example above starting from the line ``image = 197ffi.new("pixel_t[]", 800*600)``. 198 199 200API Mode, calling the C standard library 201++++++++++++++++++++++++++++++++++++++++ 202 203.. code-block:: python 204 205 # file "example_build.py" 206 207 # Note: we instantiate the same 'cffi.FFI' class as in the previous 208 # example, but call the result 'ffibuilder' now instead of 'ffi'; 209 # this is to avoid confusion with the other 'ffi' object you get below 210 211 from cffi import FFI 212 ffibuilder = FFI() 213 214 ffibuilder.set_source("_example", 215 r""" // passed to the real C compiler, 216 // contains implementation of things declared in cdef() 217 #include <sys/types.h> 218 #include <pwd.h> 219 220 // We can also define custom wrappers or other functions 221 // here (this is an example only): 222 static struct passwd *get_pw_for_root(void) { 223 return getpwuid(0); 224 } 225 """, 226 libraries=[]) # or a list of libraries to link with 227 # (more arguments like setup.py's Extension class: 228 # include_dirs=[..], extra_objects=[..], and so on) 229 230 ffibuilder.cdef(""" 231 // declarations that are shared between Python and C 232 struct passwd { 233 char *pw_name; 234 ...; // literally dot-dot-dot 235 }; 236 struct passwd *getpwuid(int uid); // defined in <pwd.h> 237 struct passwd *get_pw_for_root(void); // defined in set_source() 238 """) 239 240 if __name__ == "__main__": 241 ffibuilder.compile(verbose=True) 242 243You need to run the ``example_build.py`` script once to generate 244"source code" into the file ``_example.c`` and compile this to a 245regular C extension module. (CFFI selects either Python or C for the 246module to generate based on whether the second argument to 247:ref:`set_source() <set_source>` is ``None`` or not.) 248 249*You need a C compiler for this single step. It produces a file called 250e.g. _example.so or _example.pyd. If needed, it can be distributed in 251precompiled form like any other extension module.* 252 253Then, in your main program, you use: 254 255.. code-block:: python 256 257 from _example import ffi, lib 258 259 p = lib.getpwuid(0) 260 assert ffi.string(p.pw_name) == b'root' 261 p = lib.get_pw_for_root() 262 assert ffi.string(p.pw_name) == b'root' 263 264Note that this works independently of the exact C layout of ``struct 265passwd`` (it is "API level", as opposed to "ABI level"). It requires 266a C compiler in order to run ``example_build.py``, but it is much more 267portable than trying to get the details of the fields of ``struct 268passwd`` exactly right. Similarly, in the :ref:`cdef() <cdef>` we declared 269``getpwuid()`` as taking an ``int`` argument; on some platforms this 270might be slightly incorrect---but it does not matter. 271 272Note also that at runtime, the API mode is faster than the ABI mode. 273 274To integrate it inside a ``setup.py`` distribution with Setuptools: 275 276.. code-block:: python 277 278 from setuptools import setup 279 280 setup( 281 ... 282 setup_requires=["cffi>=1.0.0"], 283 cffi_modules=["example_build.py:ffibuilder"], 284 install_requires=["cffi>=1.0.0"], 285 ) 286 287 288.. _`if you don't have an already-installed C library to call`: 289 290API Mode, calling C sources instead of a compiled library 291+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 292 293If you want to call some library that is not precompiled, but for which 294you have C sources, then the easiest solution is to make a single 295extension module that is compiled from both the C sources of this 296library, and the additional CFFI wrappers. For example, say you start 297with the files ``pi.c`` and ``pi.h``: 298 299 .. code-block:: C 300 301 /* filename: pi.c*/ 302 # include <stdlib.h> 303 # include <math.h> 304 305 /* Returns a very crude approximation of Pi 306 given a int: a number of iteration */ 307 float pi_approx(int n){ 308 309 double i,x,y,sum=0; 310 311 for(i=0;i<n;i++){ 312 313 x=rand(); 314 y=rand(); 315 316 if (sqrt(x*x+y*y) < sqrt((double)RAND_MAX*RAND_MAX)) 317 sum++; } 318 319 return 4*(float)sum/(float)n; } 320 321 .. code-block:: C 322 323 /* filename: pi.h*/ 324 float pi_approx(int n); 325 326Create a script named ``pi_extension_build.py``, building 327the C extension: 328 329 .. code-block:: python 330 331 from cffi import FFI 332 ffibuilder = FFI() 333 334 ffibuilder.cdef("float pi_approx(int n);") 335 336 ffibuilder.set_source("_pi", # name of the output C extension 337 """ 338 #include "pi.h" 339 """, 340 sources=['pi.c'], # includes pi.c as additional sources 341 libraries=['m']) # on Unix, link with the math library 342 343 if __name__ == "__main__": 344 ffibuilder.compile(verbose=True) 345 346Build the extension: 347 348 .. code-block:: shell 349 350 python pi_extension_build.py 351 352Observe, in the working directory, the generated output files: 353``_pi.c``, ``_pi.o`` and the compiled C extension (called ``_pi.so`` on 354Linux for example). It can be called from Python: 355 356 .. code-block:: python 357 358 from _pi.lib import pi_approx 359 360 approx = pi_approx(10) 361 assert str(approx).startswith("3.") 362 363 approx = pi_approx(10000) 364 assert str(approx).startswith("3.1") 365 366 367.. _performance: 368 369Purely for performance (API level, out-of-line) 370+++++++++++++++++++++++++++++++++++++++++++++++ 371 372A variant of the `section above`__ where the goal is not to call an 373existing C library, but to compile and call some C function written 374directly in the build script: 375 376.. __: real-example_ 377 378.. code-block:: python 379 380 # file "example_build.py" 381 382 from cffi import FFI 383 ffibuilder = FFI() 384 385 ffibuilder.cdef("int foo(int *, int *, int);") 386 387 ffibuilder.set_source("_example", 388 r""" 389 static int foo(int *buffer_in, int *buffer_out, int x) 390 { 391 /* some algorithm that is seriously faster in C than in Python */ 392 } 393 """) 394 395 if __name__ == "__main__": 396 ffibuilder.compile(verbose=True) 397 398.. code-block:: python 399 400 # file "example.py" 401 402 from _example import ffi, lib 403 404 buffer_in = ffi.new("int[]", 1000) 405 # initialize buffer_in here... 406 407 # easier to do all buffer allocations in Python and pass them to C, 408 # even for output-only arguments 409 buffer_out = ffi.new("int[]", 1000) 410 411 result = lib.foo(buffer_in, buffer_out, 1000) 412 413*You need a C compiler to run example_build.py, once. It produces a 414file called e.g. _example.so or _example.pyd. If needed, it can be 415distributed in precompiled form like any other extension module.* 416 417 418.. _out-of-line-abi-level: 419 420Out-of-line, ABI level 421++++++++++++++++++++++ 422 423The out-of-line ABI mode is a mixture of the regular (API) out-of-line 424mode and the in-line ABI mode. It lets you use the ABI mode, with its 425advantages (not requiring a C compiler) and problems (crashes more 426easily). 427 428This mixture mode lets you massively reduces the import times, because 429it is slow to parse a large C header. It also allows you to do more 430detailed checkings during build-time without worrying about performance 431(e.g. calling :ref:`cdef() <cdef>` many times with small pieces of declarations, 432based on the version of libraries detected on the system). 433 434.. code-block:: python 435 436 # file "simple_example_build.py" 437 438 from cffi import FFI 439 440 ffibuilder = FFI() 441 # Note that the actual source is None 442 ffibuilder.set_source("_simple_example", None) 443 ffibuilder.cdef(""" 444 int printf(const char *format, ...); 445 """) 446 447 if __name__ == "__main__": 448 ffibuilder.compile(verbose=True) 449 450Running it once produces ``_simple_example.py``. Your main program 451only imports this generated module, not ``simple_example_build.py`` 452any more: 453 454.. code-block:: python 455 456 from _simple_example import ffi 457 458 lib = ffi.dlopen(None) # Unix: open the standard C library 459 #import ctypes.util # or, try this on Windows: 460 #lib = ffi.dlopen(ctypes.util.find_library("c")) 461 462 lib.printf(b"hi there, number %d\n", ffi.cast("int", 2)) 463 464Note that this :ref:`ffi.dlopen() <dlopen>`, unlike the one from in-line mode, 465does not invoke any additional magic to locate the library: it must be 466a path name (with or without a directory), as required by the C 467``dlopen()`` or ``LoadLibrary()`` functions. This means that 468``ffi.dlopen("libfoo.so")`` is ok, but ``ffi.dlopen("foo")`` is not. 469In the latter case, you could replace it with 470``ffi.dlopen(ctypes.util.find_library("foo"))``. Also, None is only 471recognized on Unix to open the standard C library. 472 473For distribution purposes, remember that there is a new 474``_simple_example.py`` file generated. You can either include it 475statically within your project's source files, or, with Setuptools, 476you can say in the ``setup.py``: 477 478.. code-block:: python 479 480 from setuptools import setup 481 482 setup( 483 ... 484 setup_requires=["cffi>=1.0.0"], 485 cffi_modules=["simple_example_build.py:ffibuilder"], 486 install_requires=["cffi>=1.0.0"], 487 ) 488 489In summary, this mode is useful when you wish to declare many C structures but 490do not need fast interaction with a shared object. It is useful for parsing 491binary files, for instance. 492 493 494In-line, API level 495++++++++++++++++++ 496 497The "API level + in-line" mode combination exists but is long 498deprecated. It used to be done with ``lib = ffi.verify("C header")``. 499The out-of-line variant with :ref:`set_source("modname", "C header") <set_source>` is 500preferred and avoids a number of problems when the project grows in 501size. 502 503 504.. _embedding: 505 506Embedding 507--------- 508 509*New in version 1.5.* 510 511CFFI can be used for embedding__: creating a standard 512dynamically-linked library (``.dll`` under Windows, ``.so`` elsewhere) 513which can be used from a C application. 514 515.. code-block:: python 516 517 import cffi 518 ffibuilder = cffi.FFI() 519 520 ffibuilder.embedding_api(""" 521 int do_stuff(int, int); 522 """) 523 524 ffibuilder.set_source("my_plugin", "") 525 526 ffibuilder.embedding_init_code(""" 527 from my_plugin import ffi 528 529 @ffi.def_extern() 530 def do_stuff(x, y): 531 print("adding %d and %d" % (x, y)) 532 return x + y 533 """) 534 535 ffibuilder.compile(target="plugin-1.5.*", verbose=True) 536 537This simple example creates ``plugin-1.5.dll`` or ``plugin-1.5.so`` as 538a DLL with a single exported function, ``do_stuff()``. You execute 539the script above once, with the interpreter you want to have 540internally used; it can be CPython 2.x or 3.x or PyPy. This DLL can 541then be used "as usual" from an application; the application doesn't 542need to know that it is talking with a library made with Python and 543CFFI. At runtime, when the application calls ``int do_stuff(int, 544int)``, the Python interpreter is automatically initialized and ``def 545do_stuff(x, y):`` gets called. `See the details in the documentation 546about embedding.`__ 547 548.. __: embedding.html 549.. __: embedding.html 550 551 552What actually happened? 553----------------------- 554 555The CFFI interface operates on the same level as C - you declare types 556and functions using the same syntax as you would define them in C. This 557means that most of the documentation or examples can be copied straight 558from the man pages. 559 560The declarations can contain **types, functions, constants** 561and **global variables.** What you pass to the :ref:`cdef() <cdef>` must not 562contain more than that; in particular, ``#ifdef`` or ``#include`` 563directives are not supported. The cdef in the above examples are just 564that - they declared "there is a function in the C level with this 565given signature", or "there is a struct type with this shape". 566 567In the ABI examples, the :ref:`dlopen() <dlopen>` calls load libraries manually. 568At the binary level, a program is split into multiple namespaces---a 569global one (on some platforms), plus one namespace per library. So 570``dlopen()`` returns a ``<FFILibrary>`` object, and this object has 571got as attributes all function, constant and variable symbols that are 572coming from this library and that have been declared in the 573``cdef()``. If you have several interdependent libraries to load, 574you would call ``cdef()`` only once but ``dlopen()`` several times. 575 576By opposition, the API mode works more closely like a C program: the C 577linker (static or dynamic) is responsible for finding any symbol used. 578You name the libraries in the ``libraries`` keyword argument to 579:ref:`set_source() <set_source>`, but never need to say which symbol comes 580from which library. 581Other common arguments to ``set_source()`` include ``library_dirs`` and 582``include_dirs``; all these arguments are passed to the standard 583distutils/setuptools. 584 585The :ref:`ffi.new() <new>` lines allocate C objects. They are filled 586with zeroes initially, unless the optional second argument is used. 587If specified, this argument gives an "initializer", like you can use 588with C code to initialize global variables. 589 590The actual ``lib.*()`` function calls should be obvious: it's like C. 591 592 593.. _abi-versus-api: 594 595ABI versus API 596-------------- 597 598Accessing the C library at the binary level ("ABI") is fraught 599with problems, particularly on non-Windows platforms. 600 601The most immediate drawback of the ABI level is that calling functions 602needs to go through the very general *libffi* library, which is slow 603(and not always perfectly tested on non-standard platforms). The API 604mode instead compiles a CPython C wrapper that directly invokes the 605target function. It can be massively faster (and works 606better than libffi ever will). 607 608The more fundamental reason to prefer the API mode is that *the C 609libraries are typically meant to be used with a C compiler.* You are not 610supposed to do things like guess where fields are in the structures. 611The "real example" above shows how CFFI uses a C compiler under the 612hood: this example uses :ref:`set_source(..., "C source...") <set_source>` and never 613:ref:`dlopen() <dlopen>`. When using this approach, 614we have the advantage that we can use literally "``...``" at various places in 615the :ref:`cdef() <cdef>`, and the missing information will be completed with the 616help of the C compiler. CFFI will turn this into a single C source file, 617which contains the "C source" part unmodified, followed by some 618"magic" C code and declarations derived from the ``cdef()``. When 619this C file is compiled, the resulting C extension module will contain 620all the information we need---or the C compiler will give warnings or 621errors, as usual e.g. if we misdeclare some function's signature. 622 623Note that the "C source" part from ``set_source()`` can contain 624arbitrary C code. You can use this to declare some 625more helper functions written in C. To export 626these helpers to Python, put their signature in the ``cdef()`` too. 627(You can use the ``static`` C keyword in the "C source" part, 628as in ``static int myhelper(int x) { return x * 42; }``, 629because these helpers are only 630referenced from the "magic" C code that is generated afterwards in the 631same C file.) 632 633This can be used for example to wrap "crazy" macros into more standard 634C functions. The extra layer of C can be useful for other reasons 635too, like calling functions that expect some complicated argument 636structures that you prefer to build in C rather than in Python. (On 637the other hand, if all you need is to call "function-like" macros, 638then you can directly declare them in the ``cdef()`` as if they were 639functions.) 640 641The generated piece of C code should be the same independently on the 642platform on which you run it (or the Python version), so in simple cases 643you can directly distribute the pre-generated C code and treat it as a 644regular C extension module (which depends on the ``_cffi_backend`` 645module, on CPython). The special Setuptools lines in the `example 646above`__ are meant for the more complicated cases where we need to 647regenerate the C sources as well---e.g. because the Python script that 648regenerates this file will itself look around the system to know what it 649should include or not. 650 651.. __: real-example_ 652