| 1 |
======================================================= |
| 2 |
Overview |
| 3 |
======================================================= |
| 4 |
|
| 5 |
.. contents:: |
| 6 |
|
| 7 |
|
| 8 |
The first section presents a simple working |
| 9 |
example of using CFFI to call a C function in a compiled shared object |
| 10 |
(DLL) from Python. CFFI is |
| 11 |
flexible and covers several other use cases presented in the second |
| 12 |
section. The third section shows how to export Python functions |
| 13 |
to a Python interpreter embedded in a C or C++ application. The last |
| 14 |
two sections delve deeper in the CFFI library. |
| 15 |
|
| 16 |
Make sure you have `cffi installed`__. |
| 17 |
|
| 18 |
You can find these and some other complete demos in the demo__ directory |
| 19 |
of the repository__. |
| 20 |
|
| 21 |
.. __: installation.html |
| 22 |
.. __: https://github.com/python-cffi/cffi/blob/main/demo |
| 23 |
.. __: https://github.com/python-cffi/cffi |
| 24 |
|
| 25 |
.. _out-of-line-api-level: |
| 26 |
.. _real-example: |
| 27 |
|
| 28 |
|
| 29 |
Main mode of usage |
| 30 |
------------------ |
| 31 |
|
| 32 |
The main way to use CFFI is as an interface to some already-compiled |
| 33 |
shared object which is provided by other means. Imagine that you have a |
| 34 |
system-installed shared object called ``piapprox.dll`` (Windows) or |
| 35 |
``libpiapprox.so`` (Linux and others) or ``libpiapprox.dylib`` (OS X), |
| 36 |
exporting a function ``float pi_approx(int n);`` that computes some |
| 37 |
approximation of pi given a number of iterations. You want to call |
| 38 |
this function from Python. Note this method works equally well with a |
| 39 |
static library ``piapprox.lib`` (Windows) or ``libpiapprox.a``. |
| 40 |
|
| 41 |
Create the file ``piapprox_build.py``: |
| 42 |
|
| 43 |
.. code-block:: python |
| 44 |
|
| 45 |
from cffi import FFI |
| 46 |
ffibuilder = FFI() |
| 47 |
|
| 48 |
# cdef() expects a single string declaring the C types, functions and |
| 49 |
# globals needed to use the shared object. It must be in valid C syntax. |
| 50 |
ffibuilder.cdef(""" |
| 51 |
float pi_approx(int n); |
| 52 |
""") |
| 53 |
|
| 54 |
# set_source() gives the name of the python extension module to |
| 55 |
# produce, and some C source code as a string. This C code needs |
| 56 |
# to make the declared functions, types and globals available, |
| 57 |
# so it is often just the "#include". |
| 58 |
ffibuilder.set_source("_pi_cffi", |
| 59 |
""" |
| 60 |
#include "pi.h" // the C header of the library |
| 61 |
""", |
| 62 |
libraries=['piapprox']) # library name, for the linker |
| 63 |
|
| 64 |
if __name__ == "__main__": |
| 65 |
ffibuilder.compile(verbose=True) |
| 66 |
|
| 67 |
Execute this script. If everything is OK, it should produce |
| 68 |
``_pi_cffi.c``, and then invoke the compiler on it. The produced |
| 69 |
``_pi_cffi.c`` contains a copy of the string given in :ref:`set_source() <set_source>`, |
| 70 |
in this example the ``#include "pi.h"``. Afterwards, it contains glue code |
| 71 |
for all the functions, types and globals declared in the :ref:`cdef() <cdef>` above. |
| 72 |
|
| 73 |
At runtime, you use the extension module like this: |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
from _pi_cffi import ffi, lib |
| 78 |
print(lib.pi_approx(5000)) |
| 79 |
|
| 80 |
That's all! In the rest of this page, we describe some more advanced |
| 81 |
examples and other CFFI modes. In particular, there is a complete |
| 82 |
example `if you don't have an already-installed C library to call`_. |
| 83 |
|
| 84 |
For more information about the ``cdef()`` and ``set_source()`` methods |
| 85 |
of the ``FFI`` class, see `Preparing and Distributing modules`__. |
| 86 |
|
| 87 |
.. __: cdef.html |
| 88 |
|
| 89 |
When your example works, a common alternative to running the build |
| 90 |
script manually is to have it run as part of a ``setup.py``. Here is |
| 91 |
an example using the Setuptools distribution: |
| 92 |
|
| 93 |
.. code-block:: python |
| 94 |
|
| 95 |
from setuptools import setup |
| 96 |
|
| 97 |
setup( |
| 98 |
... |
| 99 |
setup_requires=["cffi>=1.0.0"], |
| 100 |
cffi_modules=["piapprox_build:ffibuilder"], # "filename:global" |
| 101 |
install_requires=["cffi>=1.0.0"], |
| 102 |
) |
| 103 |
|
| 104 |
|
| 105 |
Other CFFI modes |
| 106 |
---------------- |
| 107 |
|
| 108 |
CFFI can be used in one of four modes: "ABI" versus "API" level, |
| 109 |
each with "in-line" or "out-of-line" preparation (or compilation). |
| 110 |
|
| 111 |
The **ABI mode** accesses libraries at the binary level, whereas the |
| 112 |
faster **API mode** accesses them with a C compiler. We explain the |
| 113 |
difference in more details below__. |
| 114 |
|
| 115 |
.. __: `abi-versus-api`_ |
| 116 |
|
| 117 |
In the **in-line mode,** everything is set up every time you import |
| 118 |
your Python code. In the **out-of-line mode,** you have a separate |
| 119 |
step of preparation (and possibly C compilation) that produces a |
| 120 |
module which your main program can then import. |
| 121 |
|
| 122 |
|
| 123 |
Simple example (ABI level, in-line) |
| 124 |
+++++++++++++++++++++++++++++++++++ |
| 125 |
|
| 126 |
May look familiar to those who have used ctypes_. |
| 127 |
|
| 128 |
.. code-block:: python |
| 129 |
|
| 130 |
>>> from cffi import FFI |
| 131 |
>>> ffi = FFI() |
| 132 |
>>> ffi.cdef(""" |
| 133 |
... int printf(const char *format, ...); // copy-pasted from the man page |
| 134 |
... """) |
| 135 |
>>> C = ffi.dlopen(None) # loads the entire C namespace |
| 136 |
>>> arg = ffi.new("char[]", b"world") # equivalent to C code: char arg[] = "world"; |
| 137 |
>>> C.printf(b"hi there, %s.\n", arg) # call printf |
| 138 |
hi there, world. |
| 139 |
17 # this is the return value |
| 140 |
>>> |
| 141 |
|
| 142 |
Note that ``char *`` arguments expect a ``bytes`` object. If you have a |
| 143 |
``str`` (or a ``unicode`` on Python 2) you need to encode it explicitly |
| 144 |
with ``somestring.encode(myencoding)``. |
| 145 |
|
| 146 |
*Python 3 on Windows:* :ref:`ffi.dlopen(None) <dlopen>` does not work. This problem |
| 147 |
is messy and not really fixable. The problem does not occur if you try |
| 148 |
to call a function from a specific DLL that exists on your system: then |
| 149 |
you use ``ffi.dlopen("path.dll")``. |
| 150 |
|
| 151 |
*This example does not call any C compiler. It works in the so-called |
| 152 |
ABI mode, which means that it will crash if you call some function or |
| 153 |
access some fields of a structure that was slightly misdeclared in the |
| 154 |
cdef().* |
| 155 |
|
| 156 |
If using a C compiler to install your module is an option, it is highly |
| 157 |
recommended to use the API mode instead. (It is also faster.) |
| 158 |
|
| 159 |
|
| 160 |
Struct/Array Example (minimal, in-line) |
| 161 |
+++++++++++++++++++++++++++++++++++++++ |
| 162 |
|
| 163 |
.. code-block:: python |
| 164 |
|
| 165 |
from cffi import FFI |
| 166 |
ffi = FFI() |
| 167 |
ffi.cdef(""" |
| 168 |
typedef struct { |
| 169 |
unsigned char r, g, b; |
| 170 |
} pixel_t; |
| 171 |
""") |
| 172 |
image = ffi.new("pixel_t[]", 800*600) |
| 173 |
|
| 174 |
f = open('data', 'rb') # binary mode -- important |
| 175 |
f.readinto(ffi.buffer(image)) |
| 176 |
f.close() |
| 177 |
|
| 178 |
image[100].r = 255 |
| 179 |
image[100].g = 192 |
| 180 |
image[100].b = 128 |
| 181 |
|
| 182 |
f = open('data', 'wb') |
| 183 |
f.write(ffi.buffer(image)) |
| 184 |
f.close() |
| 185 |
|
| 186 |
This can be used as a more flexible replacement of the struct_ and |
| 187 |
array_ modules, and replaces ctypes_. You could also call :ref:`ffi.new("pixel_t[600][800]") <new>` |
| 188 |
and get a two-dimensional array. |
| 189 |
|
| 190 |
.. _struct: http://docs.python.org/library/struct.html |
| 191 |
.. _array: http://docs.python.org/library/array.html |
| 192 |
.. _ctypes: http://docs.python.org/library/ctypes.html |
| 193 |
|
| 194 |
*This example does not call any C compiler.* |
| 195 |
|
| 196 |
This example also admits an out-of-line equivalent. It is similar to |
| 197 |
the first example `Main mode of usage`_ above, |
| 198 |
but passing ``None`` as the second argument to |
| 199 |
:ref:`ffibuilder.set_source() <set_source>`. Then in the main program you write |
| 200 |
``from _simple_example import ffi`` and then the same content as the |
| 201 |
in-line example above starting from the line ``image = |
| 202 |
ffi.new("pixel_t[]", 800*600)``. |
| 203 |
|
| 204 |
|
| 205 |
API Mode, calling the C standard library |
| 206 |
++++++++++++++++++++++++++++++++++++++++ |
| 207 |
|
| 208 |
.. code-block:: python |
| 209 |
|
| 210 |
# file "example_build.py" |
| 211 |
|
| 212 |
# Note: we instantiate the same 'cffi.FFI' class as in the previous |
| 213 |
# example, but call the result 'ffibuilder' now instead of 'ffi'; |
| 214 |
# this is to avoid confusion with the other 'ffi' object you get below |
| 215 |
|
| 216 |
from cffi import FFI |
| 217 |
ffibuilder = FFI() |
| 218 |
|
| 219 |
ffibuilder.set_source("_example", |
| 220 |
r""" // passed to the real C compiler, |
| 221 |
// contains implementation of things declared in cdef() |
| 222 |
#include <sys/types.h> |
| 223 |
#include <pwd.h> |
| 224 |
|
| 225 |
// We can also define custom wrappers or other functions |
| 226 |
// here (this is an example only): |
| 227 |
static struct passwd *get_pw_for_root(void) { |
| 228 |
return getpwuid(0); |
| 229 |
} |
| 230 |
""", |
| 231 |
libraries=[]) # or a list of libraries to link with |
| 232 |
# (more arguments like setup.py's Extension class: |
| 233 |
# include_dirs=[..], extra_objects=[..], and so on) |
| 234 |
|
| 235 |
ffibuilder.cdef(""" |
| 236 |
// declarations that are shared between Python and C |
| 237 |
struct passwd { |
| 238 |
char *pw_name; |
| 239 |
...; // literally dot-dot-dot |
| 240 |
}; |
| 241 |
struct passwd *getpwuid(int uid); // defined in <pwd.h> |
| 242 |
struct passwd *get_pw_for_root(void); // defined in set_source() |
| 243 |
""") |
| 244 |
|
| 245 |
if __name__ == "__main__": |
| 246 |
ffibuilder.compile(verbose=True) |
| 247 |
|
| 248 |
You need to run the ``example_build.py`` script once to generate |
| 249 |
"source code" into the file ``_example.c`` and compile this to a |
| 250 |
regular C extension module. (CFFI selects either Python or C for the |
| 251 |
module to generate based on whether the second argument to |
| 252 |
:ref:`set_source() <set_source>` is ``None`` or not.) |
| 253 |
|
| 254 |
*You need a C compiler for this single step. It produces a file called |
| 255 |
e.g. _example.so or _example.pyd. If needed, it can be distributed in |
| 256 |
precompiled form like any other extension module.* |
| 257 |
|
| 258 |
Then, in your main program, you use: |
| 259 |
|
| 260 |
.. code-block:: python |
| 261 |
|
| 262 |
from _example import ffi, lib |
| 263 |
|
| 264 |
p = lib.getpwuid(0) |
| 265 |
assert ffi.string(p.pw_name) == b'root' |
| 266 |
p = lib.get_pw_for_root() |
| 267 |
assert ffi.string(p.pw_name) == b'root' |
| 268 |
|
| 269 |
Note that this works independently of the exact C layout of ``struct |
| 270 |
passwd`` (it is "API level", as opposed to "ABI level"). It requires |
| 271 |
a C compiler in order to run ``example_build.py``, but it is much more |
| 272 |
portable than trying to get the details of the fields of ``struct |
| 273 |
passwd`` exactly right. Similarly, in the :ref:`cdef() <cdef>` we declared |
| 274 |
``getpwuid()`` as taking an ``int`` argument; on some platforms this |
| 275 |
might be slightly incorrect---but it does not matter. |
| 276 |
|
| 277 |
Note also that at runtime, the API mode is faster than the ABI mode. |
| 278 |
|
| 279 |
To integrate it inside a ``setup.py`` distribution with Setuptools: |
| 280 |
|
| 281 |
.. code-block:: python |
| 282 |
|
| 283 |
from setuptools import setup |
| 284 |
|
| 285 |
setup( |
| 286 |
... |
| 287 |
setup_requires=["cffi>=1.0.0"], |
| 288 |
cffi_modules=["example_build.py:ffibuilder"], |
| 289 |
install_requires=["cffi>=1.0.0"], |
| 290 |
) |
| 291 |
|
| 292 |
|
| 293 |
.. _`if you don't have an already-installed C library to call`: |
| 294 |
|
| 295 |
API Mode, calling C sources instead of a compiled library |
| 296 |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 297 |
|
| 298 |
If you want to call some library that is not precompiled, but for which |
| 299 |
you have C sources, then the easiest solution is to make a single |
| 300 |
extension module that is compiled from both the C sources of this |
| 301 |
library, and the additional CFFI wrappers. For example, say you start |
| 302 |
with the files ``pi.c`` and ``pi.h``: |
| 303 |
|
| 304 |
.. code-block:: C |
| 305 |
|
| 306 |
/* filename: pi.c*/ |
| 307 |
# include <stdlib.h> |
| 308 |
# include <math.h> |
| 309 |
|
| 310 |
/* Returns a very crude approximation of Pi |
| 311 |
given an int: a number of iterations */ |
| 312 |
float pi_approx(int n){ |
| 313 |
|
| 314 |
double i,x,y,sum=0; |
| 315 |
|
| 316 |
for(i=0;i<n;i++){ |
| 317 |
|
| 318 |
x=rand(); |
| 319 |
y=rand(); |
| 320 |
|
| 321 |
if (sqrt(x*x+y*y) < sqrt((double)RAND_MAX*RAND_MAX)) |
| 322 |
sum++; } |
| 323 |
|
| 324 |
return 4*(float)sum/(float)n; } |
| 325 |
|
| 326 |
.. code-block:: C |
| 327 |
|
| 328 |
/* filename: pi.h*/ |
| 329 |
float pi_approx(int n); |
| 330 |
|
| 331 |
Create a script named ``pi_extension_build.py``, building |
| 332 |
the C extension: |
| 333 |
|
| 334 |
.. code-block:: python |
| 335 |
|
| 336 |
from cffi import FFI |
| 337 |
ffibuilder = FFI() |
| 338 |
|
| 339 |
ffibuilder.cdef("float pi_approx(int n);") |
| 340 |
|
| 341 |
ffibuilder.set_source("_pi", # name of the output C extension |
| 342 |
""" |
| 343 |
#include "pi.h" |
| 344 |
""", |
| 345 |
sources=['pi.c'], # includes pi.c as additional sources |
| 346 |
libraries=['m']) # on Unix, link with the math library |
| 347 |
|
| 348 |
if __name__ == "__main__": |
| 349 |
ffibuilder.compile(verbose=True) |
| 350 |
|
| 351 |
Build the extension: |
| 352 |
|
| 353 |
.. code-block:: shell |
| 354 |
|
| 355 |
python pi_extension_build.py |
| 356 |
|
| 357 |
Observe, in the working directory, the generated output files: |
| 358 |
``_pi.c``, ``_pi.o`` and the compiled C extension (called ``_pi.so`` on |
| 359 |
Linux for example). It can be called from Python: |
| 360 |
|
| 361 |
.. code-block:: python |
| 362 |
|
| 363 |
from _pi.lib import pi_approx |
| 364 |
|
| 365 |
approx = pi_approx(10) |
| 366 |
assert str(approx).startswith("3.") |
| 367 |
|
| 368 |
approx = pi_approx(10000) |
| 369 |
assert str(approx).startswith("3.1") |
| 370 |
|
| 371 |
|
| 372 |
.. _performance: |
| 373 |
|
| 374 |
Purely for performance (API level, out-of-line) |
| 375 |
+++++++++++++++++++++++++++++++++++++++++++++++ |
| 376 |
|
| 377 |
A variant of the `section above`__ where the goal is not to call an |
| 378 |
existing C library, but to compile and call some C function written |
| 379 |
directly in the build script: |
| 380 |
|
| 381 |
.. __: real-example_ |
| 382 |
|
| 383 |
.. code-block:: python |
| 384 |
|
| 385 |
# file "example_build.py" |
| 386 |
|
| 387 |
from cffi import FFI |
| 388 |
ffibuilder = FFI() |
| 389 |
|
| 390 |
ffibuilder.cdef("int foo(int *, int *, int);") |
| 391 |
|
| 392 |
ffibuilder.set_source("_example", |
| 393 |
r""" |
| 394 |
static int foo(int *buffer_in, int *buffer_out, int x) |
| 395 |
{ |
| 396 |
/* some algorithm that is seriously faster in C than in Python */ |
| 397 |
} |
| 398 |
""") |
| 399 |
|
| 400 |
if __name__ == "__main__": |
| 401 |
ffibuilder.compile(verbose=True) |
| 402 |
|
| 403 |
.. code-block:: python |
| 404 |
|
| 405 |
# file "example.py" |
| 406 |
|
| 407 |
from _example import ffi, lib |
| 408 |
|
| 409 |
buffer_in = ffi.new("int[]", 1000) |
| 410 |
# initialize buffer_in here... |
| 411 |
|
| 412 |
# easier to do all buffer allocations in Python and pass them to C, |
| 413 |
# even for output-only arguments |
| 414 |
buffer_out = ffi.new("int[]", 1000) |
| 415 |
|
| 416 |
result = lib.foo(buffer_in, buffer_out, 1000) |
| 417 |
|
| 418 |
*You need a C compiler to run example_build.py, once. It produces a |
| 419 |
file called e.g. _example.so or _example.pyd. If needed, it can be |
| 420 |
distributed in precompiled form like any other extension module.* |
| 421 |
|
| 422 |
|
| 423 |
.. _out-of-line-abi-level: |
| 424 |
|
| 425 |
Out-of-line, ABI level |
| 426 |
++++++++++++++++++++++ |
| 427 |
|
| 428 |
The out-of-line ABI mode is a mixture of the regular (API) out-of-line |
| 429 |
mode and the in-line ABI mode. It lets you use the ABI mode, with its |
| 430 |
advantages (not requiring a C compiler) and problems (crashes more |
| 431 |
easily). |
| 432 |
|
| 433 |
This mixture mode lets you massively reduce the import times, because |
| 434 |
it is slow to parse a large C header. It also allows you to do more |
| 435 |
detailed checkings during build-time without worrying about performance |
| 436 |
(e.g. calling :ref:`cdef() <cdef>` many times with small pieces of declarations, |
| 437 |
based on the version of libraries detected on the system). |
| 438 |
|
| 439 |
.. code-block:: python |
| 440 |
|
| 441 |
# file "simple_example_build.py" |
| 442 |
|
| 443 |
from cffi import FFI |
| 444 |
|
| 445 |
ffibuilder = FFI() |
| 446 |
# Note that the actual source is None |
| 447 |
ffibuilder.set_source("_simple_example", None) |
| 448 |
ffibuilder.cdef(""" |
| 449 |
int printf(const char *format, ...); |
| 450 |
""") |
| 451 |
|
| 452 |
if __name__ == "__main__": |
| 453 |
ffibuilder.compile(verbose=True) |
| 454 |
|
| 455 |
Running it once produces ``_simple_example.py``. Your main program |
| 456 |
only imports this generated module, not ``simple_example_build.py`` |
| 457 |
any more: |
| 458 |
|
| 459 |
.. code-block:: python |
| 460 |
|
| 461 |
from _simple_example import ffi |
| 462 |
|
| 463 |
lib = ffi.dlopen(None) # Unix: open the standard C library |
| 464 |
#import ctypes.util # or, try this on Windows: |
| 465 |
#lib = ffi.dlopen(ctypes.util.find_library("c")) |
| 466 |
|
| 467 |
lib.printf(b"hi there, number %d\n", ffi.cast("int", 2)) |
| 468 |
|
| 469 |
Note that this :ref:`ffi.dlopen() <dlopen>`, unlike the one from in-line mode, |
| 470 |
does not invoke any additional magic to locate the library: it must be |
| 471 |
a path name (with or without a directory), as required by the C |
| 472 |
``dlopen()`` or ``LoadLibrary()`` functions. This means that |
| 473 |
``ffi.dlopen("libfoo.so")`` is ok, but ``ffi.dlopen("foo")`` is not. |
| 474 |
In the latter case, you could replace it with |
| 475 |
``ffi.dlopen(ctypes.util.find_library("foo"))``. Also, None is only |
| 476 |
recognized on Unix to open the standard C library. |
| 477 |
|
| 478 |
For distribution purposes, remember that there is a new |
| 479 |
``_simple_example.py`` file generated. You can either include it |
| 480 |
statically within your project's source files, or, with Setuptools, |
| 481 |
you can say in the ``setup.py``: |
| 482 |
|
| 483 |
.. code-block:: python |
| 484 |
|
| 485 |
from setuptools import setup |
| 486 |
|
| 487 |
setup( |
| 488 |
... |
| 489 |
setup_requires=["cffi>=1.0.0"], |
| 490 |
cffi_modules=["simple_example_build.py:ffibuilder"], |
| 491 |
install_requires=["cffi>=1.0.0"], |
| 492 |
) |
| 493 |
|
| 494 |
In summary, this mode is useful when you wish to declare many C structures but |
| 495 |
do not need fast interaction with a shared object. It is useful for parsing |
| 496 |
binary files, for instance. |
| 497 |
|
| 498 |
|
| 499 |
In-line, API level |
| 500 |
++++++++++++++++++ |
| 501 |
|
| 502 |
The "API level + in-line" mode combination exists but is long |
| 503 |
deprecated. It used to be done with ``lib = ffi.verify("C header")``. |
| 504 |
The out-of-line variant with :ref:`set_source("modname", "C header") <set_source>` is |
| 505 |
preferred and avoids a number of problems when the project grows in |
| 506 |
size. |
| 507 |
|
| 508 |
|
| 509 |
.. _embedding: |
| 510 |
|
| 511 |
Embedding |
| 512 |
--------- |
| 513 |
|
| 514 |
*New in version 1.5.* |
| 515 |
|
| 516 |
CFFI can be used for embedding__: creating a standard |
| 517 |
dynamically-linked library (``.dll`` under Windows, ``.so`` elsewhere) |
| 518 |
which can be used from a C application. |
| 519 |
|
| 520 |
.. code-block:: python |
| 521 |
|
| 522 |
import cffi |
| 523 |
ffibuilder = cffi.FFI() |
| 524 |
|
| 525 |
ffibuilder.embedding_api(""" |
| 526 |
int do_stuff(int, int); |
| 527 |
""") |
| 528 |
|
| 529 |
ffibuilder.set_source("my_plugin", "") |
| 530 |
|
| 531 |
ffibuilder.embedding_init_code(""" |
| 532 |
from my_plugin import ffi |
| 533 |
|
| 534 |
@ffi.def_extern() |
| 535 |
def do_stuff(x, y): |
| 536 |
print("adding %d and %d" % (x, y)) |
| 537 |
return x + y |
| 538 |
""") |
| 539 |
|
| 540 |
ffibuilder.compile(target="plugin-1.5.*", verbose=True) |
| 541 |
|
| 542 |
This simple example creates ``plugin-1.5.dll`` or ``plugin-1.5.so`` as |
| 543 |
a DLL with a single exported function, ``do_stuff()``. You execute |
| 544 |
the script above once, with the interpreter you want to have |
| 545 |
internally used; it can be CPython 2.x or 3.x or PyPy. This DLL can |
| 546 |
then be used "as usual" from an application; the application doesn't |
| 547 |
need to know that it is talking with a library made with Python and |
| 548 |
CFFI. At runtime, when the application calls ``int do_stuff(int, |
| 549 |
int)``, the Python interpreter is automatically initialized and ``def |
| 550 |
do_stuff(x, y):`` gets called. `See the details in the documentation |
| 551 |
about embedding.`__ |
| 552 |
|
| 553 |
.. __: embedding.html |
| 554 |
.. __: embedding.html |
| 555 |
|
| 556 |
|
| 557 |
What actually happened? |
| 558 |
----------------------- |
| 559 |
|
| 560 |
The CFFI interface operates on the same level as C - you declare types |
| 561 |
and functions using the same syntax as you would define them in C. This |
| 562 |
means that most of the documentation or examples can be copied straight |
| 563 |
from the man pages. |
| 564 |
|
| 565 |
The declarations can contain **types, functions, constants** |
| 566 |
and **global variables.** What you pass to the :ref:`cdef() <cdef>` must not |
| 567 |
contain more than that; in particular, ``#ifdef`` or ``#include`` |
| 568 |
directives are not supported. The cdef in the above examples are just |
| 569 |
that - they declared "there is a function in the C level with this |
| 570 |
given signature", or "there is a struct type with this shape". |
| 571 |
|
| 572 |
In the ABI examples, the :ref:`dlopen() <dlopen>` calls load libraries manually. |
| 573 |
At the binary level, a program is split into multiple namespaces---a |
| 574 |
global one (on some platforms), plus one namespace per library. So |
| 575 |
``dlopen()`` returns a ``<FFILibrary>`` object, and this object has |
| 576 |
got as attributes all function, constant and variable symbols that are |
| 577 |
coming from this library and that have been declared in the |
| 578 |
``cdef()``. If you have several interdependent libraries to load, |
| 579 |
you would call ``cdef()`` only once but ``dlopen()`` several times. |
| 580 |
|
| 581 |
By opposition, the API mode works more closely like a C program: the C |
| 582 |
linker (static or dynamic) is responsible for finding any symbol used. |
| 583 |
You name the libraries in the ``libraries`` keyword argument to |
| 584 |
:ref:`set_source() <set_source>`, but never need to say which symbol comes |
| 585 |
from which library. |
| 586 |
Other common arguments to ``set_source()`` include ``library_dirs`` and |
| 587 |
``include_dirs``; all these arguments are passed to the standard |
| 588 |
distutils/setuptools. |
| 589 |
|
| 590 |
The :ref:`ffi.new() <new>` lines allocate C objects. They are filled |
| 591 |
with zeroes initially, unless the optional second argument is used. |
| 592 |
If specified, this argument gives an "initializer", like you can use |
| 593 |
with C code to initialize global variables. |
| 594 |
|
| 595 |
The actual ``lib.*()`` function calls should be obvious: it's like C. |
| 596 |
|
| 597 |
|
| 598 |
.. _thread-safety: |
| 599 |
|
| 600 |
Thread Safety |
| 601 |
------------- |
| 602 |
|
| 603 |
Multithreading can be a powerful but tricky way to exploit the many cores on |
| 604 |
modern CPUs. Combining CFFI with the Python `threading` module is a convenient |
| 605 |
way to use multithreaded parallelism with a C library. |
| 606 |
|
| 607 |
On the GIL-enabled build, CFFI will release the GIL before calling into a C |
| 608 |
library. That means that it is possible to get multithreaded speedups using CFFI |
| 609 |
on both the free-threaded and GIL-enabled builds of Python. However, that also |
| 610 |
means that the GIL does not protect multithreaded shared use of C data |
| 611 |
structures exposed via FFI. |
| 612 |
|
| 613 |
If the C library you are wrapping is not thread-safe, then it is not thread-safe |
| 614 |
to use the library via Python without adding some kind of locking. If the |
| 615 |
library *is* thread-safe, then no additional locking is necessary to ensure the |
| 616 |
thread safety of CFFI itself. |
| 617 |
|
| 618 |
Let's make that concrete by wrapping some code that is not thread-safe due to |
| 619 |
use of a C global variable: |
| 620 |
|
| 621 |
.. code-block:: python |
| 622 |
|
| 623 |
from cffi import FFI |
| 624 |
ffibuilder = FFI() |
| 625 |
|
| 626 |
ffibuilder.set_source("_thread_safety_example", |
| 627 |
r""" |
| 628 |
#include <stdint.h> |
| 629 |
|
| 630 |
static int64_t value = 0; |
| 631 |
static int64_t increment(void) { |
| 632 |
value++; |
| 633 |
return value; |
| 634 |
} |
| 635 |
""", |
| 636 |
libraries=[] |
| 637 |
) |
| 638 |
|
| 639 |
ffibuilder.cdef(r""" |
| 640 |
int64_t increment(void); |
| 641 |
""" |
| 642 |
) |
| 643 |
|
| 644 |
if __name__ == "__main__": |
| 645 |
ffibuilder.compile(verbose=True) |
| 646 |
|
| 647 |
The way that ``increment`` uses the ``value`` global variable is not |
| 648 |
thread-safe. `Data races |
| 649 |
<https://en.wikipedia.org/wiki/Race_condition#Data_race>`_ are possible if two |
| 650 |
threads simultaneously call ``increment``. We can engineer that situation with a |
| 651 |
Python script that calls into the wrapper like so: |
| 652 |
|
| 653 |
.. code-block:: python |
| 654 |
|
| 655 |
import sys |
| 656 |
|
| 657 |
from concurrent.futures import ThreadPoolExecutor, wait |
| 658 |
import threading |
| 659 |
|
| 660 |
from _thread_safety_example import ffi, lib |
| 661 |
|
| 662 |
# Make races more likely by switching threads more often |
| 663 |
# on the GIL-enabled build. This has no effect on the |
| 664 |
# free-threaded build. |
| 665 |
sys.setswitchinterval(.0000001) |
| 666 |
|
| 667 |
N_WORKERS = 4 |
| 668 |
|
| 669 |
l = threading.Lock() |
| 670 |
|
| 671 |
def work(): |
| 672 |
lib.increment() |
| 673 |
|
| 674 |
def run_thread_pool(): |
| 675 |
with ThreadPoolExecutor(max_workers=N_WORKERS) as tpe: |
| 676 |
try: |
| 677 |
futures = [tpe.submit(work) for _ in range(100000)] |
| 678 |
# block until all work finishes |
| 679 |
wait(futures) |
| 680 |
finally: |
| 681 |
# check for exceptions in worker threads |
| 682 |
[f.result() for f in futures] |
| 683 |
|
| 684 |
|
| 685 |
run_thread_pool() |
| 686 |
|
| 687 |
print(lib.increment()) |
| 688 |
|
| 689 |
On the system used to run this example by the author, this script prints random |
| 690 |
results, with possible result values ranging from 99960 to 99980, indicating |
| 691 |
that, on average, races happen a few dozen times over the hundred thousand loop |
| 692 |
iterations. The results you get will depend on your hardware, system |
| 693 |
configuration, and Python interpreter version. |
| 694 |
|
| 695 |
Note that races are relatively rare. The CFFI bindings and Python interpreter |
| 696 |
add enough overhead that it is not very likely for two threads to simultaneously |
| 697 |
increment the static integer. This can make code *appear* to be sequentially |
| 698 |
consistent for small sample sizes, when it is in fact not consistent. See `this |
| 699 |
tutorial |
| 700 |
<https://github.com/facebookincubator/ft_utils/blob/main/docs/fine_grained_synchronization.md#understanding-the-gil>`_ |
| 701 |
for more examples of how the GIL and Python overhead can mask thread safety |
| 702 |
issues that only manifest under production load. |
| 703 |
|
| 704 |
We can make the above example script thread-safe by using a lock: |
| 705 |
|
| 706 |
.. code-block:: python |
| 707 |
|
| 708 |
l = threading.Lock() |
| 709 |
|
| 710 |
def work(): |
| 711 |
l.acquire() |
| 712 |
lib.increment() |
| 713 |
l.release() |
| 714 |
|
| 715 |
The `threading.Lock` ensures only one thread can call into the wrapped C library |
| 716 |
at a time. Any thread that calls ``l.acquire()`` while another thread has |
| 717 |
already acquired the lock will block until the lock is released. |
| 718 |
|
| 719 |
Using a global lock like this is necessary if it is not safe for more than one |
| 720 |
thread to simultaneously call into any part of the library. This is the case if |
| 721 |
the library relies on global state that does not have any explicit |
| 722 |
synchronization. Libraries like this are not `re-entrant |
| 723 |
<https://en.wikipedia.org/wiki/Reentrancy_(computing)>`_. |
| 724 |
|
| 725 |
Libraries that are re-entrant but not thread-safe are usually structured such |
| 726 |
that two threads can simultaneously use the library so long as the threads do |
| 727 |
not simultaneously mutate shared references to an object. For libraries like |
| 728 |
this you will want to use a per-object lock instead of a global lock. Keep in |
| 729 |
mind in this case that any program with more than one lock can lead to a |
| 730 |
`deadlock <https://en.wikipedia.org/wiki/Deadlock_(computer_science)>`_ and care |
| 731 |
must be taken to avoid situations where two threads can deadlock. |
| 732 |
|
| 733 |
If it is a programming error for two threads to simultaneously share an object, |
| 734 |
you might acquire a `threading.Lock` object named ``l`` like this: |
| 735 |
|
| 736 |
.. code-block:: python |
| 737 |
|
| 738 |
if not l.acquire(blocking=False): |
| 739 |
raise RuntimeError("Multithreaded use is not supported") |
| 740 |
|
| 741 |
# call into the unsafe library or use an unsafe object |
| 742 |
|
| 743 |
l.release() |
| 744 |
|
| 745 |
This prevents deadlocks, since `l.acquire(blocking=False)` returns `False` |
| 746 |
immediately if the lock is already acquired by another thread. |
| 747 |
|
| 748 |
If you know that the C library you are wrapping is thread-safe, no additional |
| 749 |
locking is necessary to make the CFFI bindings thread-safe. Please report thread |
| 750 |
safety bugs that you suspect are due to issues in the generated CFFI bindings. |
| 751 |
|
| 752 |
If you publish CFFI bindings for a library, you should document the thread |
| 753 |
safety guarantees of your bindings. It may make sense to add locking into the |
| 754 |
bindings but it might also make sense to clearly document the bindings are not |
| 755 |
thread-safe and it is up to users to ensure appropriate synchronization or |
| 756 |
exclusive access if users do want to use the bindings in a thread pool. |
| 757 |
|
| 758 |
See the Python free-threading guide page on `improving the thread safety of |
| 759 |
Python code |
| 760 |
<https://py-free-threading.github.io/porting/#thread-safety-of-pure-python-code>`_ |
| 761 |
for more information about updating a Python library with thread safety in mind. |
| 762 |
|
| 763 |
You can validate the thread safety of your library by running multithreaded |
| 764 |
tests using `Thread Sanitizer |
| 765 |
<https://clang.llvm.org/docs/ThreadSanitizer.html>`_. See the Python |
| 766 |
free-threading guide page on `using Thread Sanitizer to detect thread safety |
| 767 |
issues <https://py-free-threading.github.io/thread_sanitizer/>`_ for more |
| 768 |
details. |
| 769 |
|
| 770 |
.. _abi-versus-api: |
| 771 |
|
| 772 |
ABI versus API |
| 773 |
-------------- |
| 774 |
|
| 775 |
Accessing the C library at the binary level ("ABI") is fraught |
| 776 |
with problems, particularly on non-Windows platforms. |
| 777 |
|
| 778 |
The most immediate drawback of the ABI level is that calling functions |
| 779 |
needs to go through the very general *libffi* library, which is slow |
| 780 |
(and not always perfectly tested on non-standard platforms). The API |
| 781 |
mode instead compiles a CPython C wrapper that directly invokes the |
| 782 |
target function. It can be massively faster (and works |
| 783 |
better than libffi ever will). |
| 784 |
|
| 785 |
The more fundamental reason to prefer the API mode is that *the C |
| 786 |
libraries are typically meant to be used with a C compiler.* You are not |
| 787 |
supposed to do things like guess where fields are in the structures. |
| 788 |
The "real example" above shows how CFFI uses a C compiler under the |
| 789 |
hood: this example uses :ref:`set_source(..., "C source...") <set_source>` and never |
| 790 |
:ref:`dlopen() <dlopen>`. When using this approach, |
| 791 |
we have the advantage that we can use literally "``...``" at various places in |
| 792 |
the :ref:`cdef() <cdef>`, and the missing information will be completed with the |
| 793 |
help of the C compiler. CFFI will turn this into a single C source file, |
| 794 |
which contains the "C source" part unmodified, followed by some |
| 795 |
"magic" C code and declarations derived from the ``cdef()``. When |
| 796 |
this C file is compiled, the resulting C extension module will contain |
| 797 |
all the information we need---or the C compiler will give warnings or |
| 798 |
errors, as usual e.g. if we misdeclare some function's signature. |
| 799 |
|
| 800 |
Note that the "C source" part from ``set_source()`` can contain |
| 801 |
arbitrary C code. You can use this to declare some |
| 802 |
more helper functions written in C. To export |
| 803 |
these helpers to Python, put their signature in the ``cdef()`` too. |
| 804 |
(You can use the ``static`` C keyword in the "C source" part, |
| 805 |
as in ``static int myhelper(int x) { return x * 42; }``, |
| 806 |
because these helpers are only |
| 807 |
referenced from the "magic" C code that is generated afterwards in the |
| 808 |
same C file.) |
| 809 |
|
| 810 |
This can be used for example to wrap "crazy" macros into more standard |
| 811 |
C functions. The extra layer of C can be useful for other reasons |
| 812 |
too, like calling functions that expect some complicated argument |
| 813 |
structures that you prefer to build in C rather than in Python. (On |
| 814 |
the other hand, if all you need is to call "function-like" macros, |
| 815 |
then you can directly declare them in the ``cdef()`` as if they were |
| 816 |
functions.) |
| 817 |
|
| 818 |
The generated piece of C code should be the same independently on the |
| 819 |
platform on which you run it (or the Python version), so in simple cases |
| 820 |
you can directly distribute the pre-generated C code and treat it as a |
| 821 |
regular C extension module (which depends on the ``_cffi_backend`` |
| 822 |
module, on CPython). The special Setuptools lines in the `example |
| 823 |
above`__ are meant for the more complicated cases where we need to |
| 824 |
regenerate the C sources as well---e.g. because the Python script that |
| 825 |
regenerates this file will itself look around the system to know what it |
| 826 |
should include or not. |
| 827 |
|
| 828 |
.. __: real-example_ |