• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1================================
2Using the ffi/lib objects
3================================
4
5.. contents::
6
7Keep this page under your pillow.
8
9
10.. _working:
11
12Working with pointers, structures and arrays
13--------------------------------------------
14
15The C code's integers and floating-point values are mapped to Python's
16regular ``int``, ``long`` and ``float``.  Moreover, the C type ``char``
17corresponds to single-character strings in Python.  (If you want it to
18map to small integers, use either ``signed char`` or ``unsigned char``.)
19
20Similarly, the C type ``wchar_t`` corresponds to single-character
21unicode strings.  Note that in some situations (a narrow Python build
22with an underlying 4-bytes wchar_t type), a single wchar_t character
23may correspond to a pair of surrogates, which is represented as a
24unicode string of length 2.  If you need to convert such a 2-chars
25unicode string to an integer, ``ord(x)`` does not work; use instead
26``int(ffi.cast('wchar_t', x))``.
27
28*New in version 1.11:* in addition to ``wchar_t``, the C types
29``char16_t`` and ``char32_t`` work the same but with a known fixed size.
30In previous versions, this could be achieved using ``uint16_t`` and
31``int32_t`` but without automatic conversion to Python unicodes.
32
33Pointers, structures and arrays are more complex: they don't have an
34obvious Python equivalent.  Thus, they correspond to objects of type
35``cdata``, which are printed for example as
36``<cdata 'struct foo_s *' 0xa3290d8>``.
37
38``ffi.new(ctype, [initializer])``: this function builds and returns a
39new cdata object of the given ``ctype``.  The ctype is usually some
40constant string describing the C type.  It must be a pointer or array
41type.  If it is a pointer, e.g. ``"int *"`` or ``struct foo *``, then
42it allocates the memory for one ``int`` or ``struct foo``.  If it is
43an array, e.g. ``int[10]``, then it allocates the memory for ten
44``int``.  In both cases the returned cdata is of type ``ctype``.
45
46The memory is initially filled with zeros.  An initializer can be given
47too, as described later.
48
49Example::
50
51    >>> ffi.new("int *")
52    <cdata 'int *' owning 4 bytes>
53    >>> ffi.new("int[10]")
54    <cdata 'int[10]' owning 40 bytes>
55
56    >>> ffi.new("char *")          # allocates only one char---not a C string!
57    <cdata 'char *' owning 1 bytes>
58    >>> ffi.new("char[]", "foobar")  # this allocates a C string, ending in \0
59    <cdata 'char[]' owning 7 bytes>
60
61Unlike C, the returned pointer object has *ownership* on the allocated
62memory: when this exact object is garbage-collected, then the memory is
63freed.  If, at the level of C, you store a pointer to the memory
64somewhere else, then make sure you also keep the object alive for as
65long as needed.  (This also applies if you immediately cast the returned
66pointer to a pointer of a different type: only the original object has
67ownership, so you must keep it alive.  As soon as you forget it, then
68the casted pointer will point to garbage!  In other words, the ownership
69rules are attached to the *wrapper* cdata objects: they are not, and
70cannot, be attached to the underlying raw memory.)  Example:
71
72.. code-block:: python
73
74    global_weakkeydict = weakref.WeakKeyDictionary()
75
76    def make_foo():
77        s1   = ffi.new("struct foo *")
78        fld1 = ffi.new("struct bar *")
79        fld2 = ffi.new("struct bar *")
80        s1.thefield1 = fld1
81        s1.thefield2 = fld2
82        # here the 'fld1' and 'fld2' object must not go away,
83        # otherwise 's1.thefield1/2' will point to garbage!
84        global_weakkeydict[s1] = (fld1, fld2)
85        # now 's1' keeps alive 'fld1' and 'fld2'.  When 's1' goes
86        # away, then the weak dictionary entry will be removed.
87        return s1
88
89Usually you don't need a weak dict: for example, to call a function with
90a ``char * *`` argument that contains a pointer to a ``char *`` pointer,
91it is enough to do this:
92
93.. code-block:: python
94
95    p = ffi.new("char[]", "hello, world")    # p is a 'char *'
96    q = ffi.new("char **", p)                # q is a 'char **'
97    lib.myfunction(q)
98    # p is alive at least until here, so that's fine
99
100However, this is always wrong (usage of freed memory):
101
102.. code-block:: python
103
104    p = ffi.new("char **", ffi.new("char[]", "hello, world"))
105    # WRONG!  as soon as p is built, the inner ffi.new() gets freed!
106
107This is wrong too, for the same reason:
108
109.. code-block:: python
110
111    p = ffi.new("struct my_stuff")
112    p.foo = ffi.new("char[]", "hello, world")
113    # WRONG!  as soon as p.foo is set, the ffi.new() gets freed!
114
115
116The cdata objects support mostly the same operations as in C: you can
117read or write from pointers, arrays and structures.  Dereferencing a
118pointer is done usually in C with the syntax ``*p``, which is not valid
119Python, so instead you have to use the alternative syntax ``p[0]``
120(which is also valid C).  Additionally, the ``p.x`` and ``p->x``
121syntaxes in C both become ``p.x`` in Python.
122
123We have ``ffi.NULL`` to use in the same places as the C ``NULL``.
124Like the latter, it is actually defined to be ``ffi.cast("void *",
1250)``.  For example, reading a NULL pointer returns a ``<cdata 'type *'
126NULL>``, which you can check for e.g. by comparing it with
127``ffi.NULL``.
128
129There is no general equivalent to the ``&`` operator in C (because it
130would not fit nicely in the model, and it does not seem to be needed
131here).  There is `ffi.addressof()`__, but only for some cases.  You
132cannot take the "address" of a number in Python, for example; similarly,
133you cannot take the address of a CFFI pointer.  If you have this kind
134of C code::
135
136    int x, y;
137    fetch_size(&x, &y);
138
139    opaque_t *handle;      // some opaque pointer
140    init_stuff(&handle);   // initializes the variable 'handle'
141    more_stuff(handle);    // pass the handle around to more functions
142
143then you need to rewrite it like this, replacing the variables in C
144with what is logically pointers to the variables:
145
146.. code-block:: python
147
148    px = ffi.new("int *")
149    py = ffi.new("int *")              arr = ffi.new("int[2]")
150    lib.fetch_size(px, py)    -OR-     lib.fetch_size(arr, arr + 1)
151    x = px[0]                          x = arr[0]
152    y = py[0]                          y = arr[1]
153
154    p_handle = ffi.new("opaque_t **")
155    lib.init_stuff(p_handle)   # pass the pointer to the 'handle' pointer
156    handle = p_handle[0]       # now we can read 'handle' out of 'p_handle'
157    lib.more_stuff(handle)
158
159.. __: ref.html#ffi-addressof
160
161
162Any operation that would in C return a pointer or array or struct type
163gives you a fresh cdata object.  Unlike the "original" one, these fresh
164cdata objects don't have ownership: they are merely references to
165existing memory.
166
167As an exception to the above rule, dereferencing a pointer that owns a
168*struct* or *union* object returns a cdata struct or union object
169that "co-owns" the same memory.  Thus in this case there are two
170objects that can keep the same memory alive.  This is done for cases where
171you really want to have a struct object but don't have any convenient
172place to keep alive the original pointer object (returned by
173``ffi.new()``).
174
175Example:
176
177.. code-block:: python
178
179    # void somefunction(int *);
180
181    x = ffi.new("int *")      # allocate one int, and return a pointer to it
182    x[0] = 42                 # fill it
183    lib.somefunction(x)       # call the C function
184    print x[0]                # read the possibly-changed value
185
186The equivalent of C casts are provided with ``ffi.cast("type", value)``.
187They should work in the same cases as they do in C.  Additionally, this
188is the only way to get cdata objects of integer or floating-point type::
189
190    >>> x = ffi.cast("int", 42)
191    >>> x
192    <cdata 'int' 42>
193    >>> int(x)
194    42
195
196To cast a pointer to an int, cast it to ``intptr_t`` or ``uintptr_t``,
197which are defined by C to be large enough integer types (example on 32
198bits)::
199
200    >>> int(ffi.cast("intptr_t", pointer_cdata))    # signed
201    -1340782304
202    >>> int(ffi.cast("uintptr_t", pointer_cdata))   # unsigned
203    2954184992L
204
205The initializer given as the optional second argument to ``ffi.new()``
206can be mostly anything that you would use as an initializer for C code,
207with lists or tuples instead of using the C syntax ``{ .., .., .. }``.
208Example::
209
210    typedef struct { int x, y; } foo_t;
211
212    foo_t v = { 1, 2 };            // C syntax
213    v = ffi.new("foo_t *", [1, 2]) # CFFI equivalent
214
215    foo_t v = { .y=1, .x=2 };                // C99 syntax
216    v = ffi.new("foo_t *", {'y': 1, 'x': 2}) # CFFI equivalent
217
218Like C, arrays of chars can also be initialized from a string, in
219which case a terminating null character is appended implicitly::
220
221    >>> x = ffi.new("char[]", "hello")
222    >>> x
223    <cdata 'char[]' owning 6 bytes>
224    >>> len(x)        # the actual size of the array
225    6
226    >>> x[5]          # the last item in the array
227    '\x00'
228    >>> x[0] = 'H'    # change the first item
229    >>> ffi.string(x) # interpret 'x' as a regular null-terminated string
230    'Hello'
231
232Similarly, arrays of wchar_t or char16_t or char32_t can be initialized
233from a unicode string,
234and calling ``ffi.string()`` on the cdata object returns the current unicode
235string stored in the source array (adding surrogates if necessary).
236See the `Unicode character types`__ section for more details.
237
238.. __: ref.html#unichar
239
240Note that unlike Python lists or tuples, but like C, you *cannot* index in
241a C array from the end using negative numbers.
242
243More generally, the C array types can have their length unspecified in C
244types, as long as their length can be derived from the initializer, like
245in C::
246
247    int array[] = { 1, 2, 3, 4 };           // C syntax
248    array = ffi.new("int[]", [1, 2, 3, 4])  # CFFI equivalent
249
250As an extension, the initializer can also be just a number, giving
251the length (in case you just want zero-initialization)::
252
253    int array[1000];                  // C syntax
254    array = ffi.new("int[1000]")      # CFFI 1st equivalent
255    array = ffi.new("int[]", 1000)    # CFFI 2nd equivalent
256
257This is useful if the length is not actually a constant, to avoid things
258like ``ffi.new("int[%d]" % x)``.  Indeed, this is not recommended:
259``ffi`` normally caches the string ``"int[]"`` to not need to re-parse
260it all the time.
261
262The C99 variable-sized structures are supported too, as long as the
263initializer says how long the array should be:
264
265.. code-block:: python
266
267    # typedef struct { int x; int y[]; } foo_t;
268
269    p = ffi.new("foo_t *", [5, [6, 7, 8]]) # length 3
270    p = ffi.new("foo_t *", [5, 3])         # length 3 with 0 in the array
271    p = ffi.new("foo_t *", {'y': 3})       # length 3 with 0 everywhere
272
273Finally, note that any Python object used as initializer can also be
274used directly without ``ffi.new()`` in assignments to array items or
275struct fields.  In fact, ``p = ffi.new("T*", initializer)`` is
276equivalent to ``p = ffi.new("T*"); p[0] = initializer``.  Examples:
277
278.. code-block:: python
279
280    # if 'p' is a <cdata 'int[5][5]'>
281    p[2] = [10, 20]             # writes to p[2][0] and p[2][1]
282
283    # if 'p' is a <cdata 'foo_t *'>, and foo_t has fields x, y and z
284    p[0] = {'x': 10, 'z': 20}   # writes to p.x and p.z; p.y unmodified
285
286    # if, on the other hand, foo_t has a field 'char a[5]':
287    p.a = "abc"                 # writes 'a', 'b', 'c' and '\0'; p.a[4] unmodified
288
289In function calls, when passing arguments, these rules can be used too;
290see `Function calls`_.
291
292
293Python 3 support
294----------------
295
296Python 3 is supported, but the main point to note is that the ``char`` C
297type corresponds to the ``bytes`` Python type, and not ``str``.  It is
298your responsibility to encode/decode all Python strings to bytes when
299passing them to or receiving them from CFFI.
300
301This only concerns the ``char`` type and derivative types; other parts
302of the API that accept strings in Python 2 continue to accept strings in
303Python 3.
304
305
306An example of calling a main-like thing
307---------------------------------------
308
309Imagine we have something like this:
310
311.. code-block:: python
312
313   from cffi import FFI
314   ffi = FFI()
315   ffi.cdef("""
316      int main_like(int argv, char *argv[]);
317   """)
318   lib = ffi.dlopen("some_library.so")
319
320Now, everything is simple, except, how do we create the ``char**`` argument
321here?
322The first idea:
323
324.. code-block:: python
325
326   lib.main_like(2, ["arg0", "arg1"])
327
328does not work, because the initializer receives two Python ``str`` objects
329where it was expecting ``<cdata 'char *'>`` objects.  You need to use
330``ffi.new()`` explicitly to make these objects:
331
332.. code-block:: python
333
334   lib.main_like(2, [ffi.new("char[]", "arg0"),
335                     ffi.new("char[]", "arg1")])
336
337Note that the two ``<cdata 'char[]'>`` objects are kept alive for the
338duration of the call: they are only freed when the list itself is freed,
339and the list is only freed when the call returns.
340
341If you want instead to build an "argv" variable that you want to reuse,
342then more care is needed:
343
344.. code-block:: python
345
346   # DOES NOT WORK!
347   argv = ffi.new("char *[]", [ffi.new("char[]", "arg0"),
348                               ffi.new("char[]", "arg1")])
349
350In the above example, the inner "arg0" string is deallocated as soon
351as "argv" is built.  You have to make sure that you keep a reference
352to the inner "char[]" objects, either directly or by keeping the list
353alive like this:
354
355.. code-block:: python
356
357   argv_keepalive = [ffi.new("char[]", "arg0"),
358                     ffi.new("char[]", "arg1")]
359   argv = ffi.new("char *[]", argv_keepalive)
360
361
362Function calls
363--------------
364
365When calling C functions, passing arguments follows mostly the same
366rules as assigning to structure fields, and the return value follows the
367same rules as reading a structure field.  For example:
368
369.. code-block:: python
370
371    # int foo(short a, int b);
372
373    n = lib.foo(2, 3)     # returns a normal integer
374    lib.foo(40000, 3)     # raises OverflowError
375
376You can pass to ``char *`` arguments a normal Python string (but don't
377pass a normal Python string to functions that take a ``char *``
378argument and may mutate it!):
379
380.. code-block:: python
381
382    # size_t strlen(const char *);
383
384    assert lib.strlen("hello") == 5
385
386You can also pass unicode strings as ``wchar_t *`` or ``char16_t *`` or
387``char32_t *`` arguments.  Note that
388the C language makes no difference between argument declarations that
389use ``type *`` or ``type[]``.  For example, ``int *`` is fully
390equivalent to ``int[]`` (or even ``int[5]``; the 5 is ignored).  For CFFI,
391this means that you can always pass arguments that can be converted to
392either ``int *`` or ``int[]``.  For example:
393
394.. code-block:: python
395
396    # void do_something_with_array(int *array);
397
398    lib.do_something_with_array([1, 2, 3, 4, 5])    # works for int[]
399
400See `Reference: conversions`__ for a similar way to pass ``struct foo_s
401*`` arguments---but in general, it is clearer in this case to pass
402``ffi.new('struct foo_s *', initializer)``.
403
404__ ref.html#conversions
405
406CFFI supports passing and returning structs and unions to functions and
407callbacks.  Example:
408
409.. code-block:: python
410
411    # struct foo_s { int a, b; };
412    # struct foo_s function_returning_a_struct(void);
413
414    myfoo = lib.function_returning_a_struct()
415    # `myfoo`: <cdata 'struct foo_s' owning 8 bytes>
416
417For performance, non-variadic API-level functions that you get by
418writing ``lib.some_function`` are not ``<cdata>``
419objects, but an object of a different type (on CPython, ``<built-in
420function>``).  This means you cannot pass them directly to some other C
421function expecting a function pointer argument.  Only ``ffi.typeof()``
422works on them.  To get a cdata containing a regular function pointer,
423use ``ffi.addressof(lib, "name")``.
424
425There are a few (obscure) limitations to the supported argument and
426return types.  These limitations come from libffi and apply only to
427calling ``<cdata>`` function pointers; in other words, they don't
428apply to non-variadic ``cdef()``-declared functions if you are using
429the API mode.  The limitations are that you cannot pass directly as
430argument or return type:
431
432* a union (but a *pointer* to a union is fine);
433
434* a struct which uses bitfields (but a *pointer* to such a struct is
435  fine);
436
437* a struct that was declared with "``...``" in the ``cdef()``.
438
439In API mode, you can work around these limitations: for example, if you
440need to call such a function pointer from Python, you can instead write
441a custom C function that accepts the function pointer and the real
442arguments and that does the call from C.  Then declare that custom C
443function in the ``cdef()`` and use it from Python.
444
445
446Variadic function calls
447-----------------------
448
449Variadic functions in C (which end with "``...``" as their last
450argument) can be declared and called normally, with the exception that
451all the arguments passed in the variable part *must* be cdata objects.
452This is because it would not be possible to guess, if you wrote this::
453
454    lib.printf("hello, %d\n", 42)   # doesn't work!
455
456that you really meant the 42 to be passed as a C ``int``, and not a
457``long`` or ``long long``.  The same issue occurs with ``float`` versus
458``double``.  So you have to force cdata objects of the C type you want,
459if necessary with ``ffi.cast()``:
460
461.. code-block:: python
462
463    lib.printf("hello, %d\n", ffi.cast("int", 42))
464    lib.printf("hello, %ld\n", ffi.cast("long", 42))
465    lib.printf("hello, %f\n", ffi.cast("double", 42))
466
467But of course:
468
469.. code-block:: python
470
471    lib.printf("hello, %s\n", ffi.new("char[]", "world"))
472
473Note that if you are using ``dlopen()``, the function declaration in the
474``cdef()`` must match the original one in C exactly, as usual --- in
475particular, if this function is variadic in C, then its ``cdef()``
476declaration must also be variadic.  You cannot declare it in the
477``cdef()`` with fixed arguments instead, even if you plan to only call
478it with these argument types.  The reason is that some architectures
479have a different calling convention depending on whether the function
480signature is fixed or not.  (On x86-64, the difference can sometimes be
481seen in PyPy's JIT-generated code if some arguments are ``double``.)
482
483Note that the function signature ``int foo();`` is interpreted by CFFI
484as equivalent to ``int foo(void);``.  This differs from the C standard,
485in which ``int foo();`` is really like ``int foo(...);`` and can be
486called with any arguments.  (This feature of C is a pre-C89 relic: the
487arguments cannot be accessed at all in the body of ``foo()`` without
488relying on compiler-specific extensions.  Nowadays virtually all code
489with ``int foo();`` really means ``int foo(void);``.)
490
491
492Memory pressure (PyPy)
493----------------------
494
495This paragraph applies only to PyPy, because its garbage collector (GC)
496is different from CPython's.  It is very common in C code to have pairs
497of functions, one which performs memory allocations or acquires other
498resources, and the other which frees them again.  Depending on how you
499structure your Python code, the freeing function is only called when the
500GC decides a particular (Python) object can be freed.  This occurs
501notably in these cases:
502
503* If you use a ``__del__()`` method to call the freeing function.
504
505* If you use ``ffi.gc()`` without also using ``ffi.release()``.
506
507* This does not occur if you call the freeing function at a
508  deterministic time, like in a regular ``try: finally:`` block.  It
509  does however occur *inside a generator---* if the generator is not
510  explicitly exhausted but forgotten at a ``yield`` point, then the code
511  in the enclosing ``finally`` block is only invoked at the next GC.
512
513In these cases, you may have to use the built-in function
514``__pypy__.add_memory_pressure(n)``.  Its argument ``n`` is an estimate
515of how much memory pressure to add.  For example, if the pair of C
516functions that we are talking about is ``malloc(n)`` and ``free()`` or
517similar, you would call ``__pypy__.add_memory_pressure(n)`` after
518``malloc(n)``.  Doing so is not always a complete answer to the problem,
519but it makes the next GC occur earlier, which is often enough.
520
521The same applies if the memory allocations are indirect, e.g. the C
522function allocates some internal data structures.  In that case, call
523``__pypy__.add_memory_pressure(n)`` with an argument ``n`` that is an
524rough estimation.  Knowing the exact size is not important, and memory
525pressure doesn't have to be manually brought down again after calling
526the freeing function.  If you are writing wrappers for the allocating /
527freeing pair of functions, you should probably call
528``__pypy__.add_memory_pressure()`` in the former even if the user may
529invoke the latter at a known point with a ``finally:`` block.
530
531In case this solution is not sufficient, or if the acquired resource is
532not memory but something else more limited (like file descriptors), then
533there is no better way than restructuring your code to make sure the
534freeing function is called at a known point and not indirectly by the
535GC.
536
537Note that in PyPy <= 5.6 the discussion above also applies to
538``ffi.new()``.  In more recent versions of PyPy, both ``ffi.new()`` and
539``ffi.new_allocator()()`` automatically account for the memory pressure
540they create.  (In case you need to support both older and newer PyPy's,
541try calling ``__pypy__.add_memory_pressure()`` anyway; it is better to
542overestimate than not account for the memory pressure.)
543
544
545.. _extern-python:
546.. _`extern "Python"`:
547
548Extern "Python" (new-style callbacks)
549-------------------------------------
550
551When the C code needs a pointer to a function which invokes back a
552Python function of your choice, here is how you do it in the
553out-of-line API mode.  The next section about Callbacks_ describes the
554ABI-mode solution.
555
556This is *new in version 1.4.*  Use old-style Callbacks_ if backward
557compatibility is an issue.  (The original callbacks are slower to
558invoke and have the same issue as libffi's callbacks; notably, see the
559warning__.  The new style described in the present section does not
560use libffi's callbacks at all.)
561
562.. __: Callbacks_
563
564In the builder script, declare in the cdef a function prefixed with
565``extern "Python"``::
566
567    ffibuilder.cdef("""
568        extern "Python" int my_callback(int, int);
569
570        void library_function(int(*callback)(int, int));
571    """)
572    ffibuilder.set_source("_my_example", r"""
573        #include <some_library.h>
574    """)
575
576The function ``my_callback()`` is then implemented in Python inside
577your application's code::
578
579    from _my_example import ffi, lib
580
581    @ffi.def_extern()
582    def my_callback(x, y):
583        return 42
584
585You obtain a ``<cdata>`` pointer-to-function object by getting
586``lib.my_callback``.  This ``<cdata>`` can be passed to C code and
587then works like a callback: when the C code calls this function
588pointer, the Python function ``my_callback`` is called.  (You need
589to pass ``lib.my_callback`` to C code, and not ``my_callback``: the
590latter is just the Python function above, which cannot be passed to C.)
591
592CFFI implements this by defining ``my_callback`` as a static C
593function, written after the ``set_source()`` code.  The ``<cdata>``
594then points to this function.  What this function does is invoke the
595Python function object that is, at runtime, attached with
596``@ffi.def_extern()``.
597
598The ``@ffi.def_extern()`` decorator should be applied to **global
599functions,** one for each ``extern "Python"`` function of the same
600name.
601
602To support some corner cases, it is possible to redefine the attached
603Python function by calling ``@ffi.def_extern()`` again for the same
604name---but this is not recommended!  Better attach a single global
605Python function for this name, and write it more flexibly in the first
606place.  This is because each ``extern "Python"`` function turns into
607only one C function.  Calling ``@ffi.def_extern()`` again changes this
608function's C logic to call the new Python function; the old Python
609function is not callable any more.  The C function pointer you get
610from ``lib.my_function`` is always this C function's address, i.e. it
611remains the same.
612
613Extern "Python" and ``void *`` arguments
614~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
615
616As described just before, you cannot use ``extern "Python"`` to make a
617variable number of C function pointers.  However, achieving that
618result is not possible in pure C code either.  For this reason, it is
619usual for C to define callbacks with a ``void *data`` argument.  You
620can use ``ffi.new_handle()`` and ``ffi.from_handle()`` to pass a
621Python object through this ``void *`` argument.  For example, if the C
622type of the callbacks is::
623
624    typedef void (*event_cb_t)(event_t *evt, void *userdata);
625
626and you register events by calling this function::
627
628    void event_cb_register(event_cb_t cb, void *userdata);
629
630Then you would write this in the build script::
631
632    ffibuilder.cdef("""
633        typedef ... event_t;
634        typedef void (*event_cb_t)(event_t *evt, void *userdata);
635        void event_cb_register(event_cb_t cb, void *userdata);
636
637        extern "Python" void my_event_callback(event_t *, void *);
638    """)
639    ffibuilder.set_source("_demo_cffi", r"""
640        #include <the_event_library.h>
641    """)
642
643and in your main application you register events like this::
644
645    from _demo_cffi import ffi, lib
646
647    class Widget(object):
648        def __init__(self):
649            userdata = ffi.new_handle(self)
650            self._userdata = userdata     # must keep this alive!
651            lib.event_cb_register(lib.my_event_callback, userdata)
652
653        def process_event(self, evt):
654            print "got event!"
655
656    @ffi.def_extern()
657    def my_event_callback(evt, userdata):
658        widget = ffi.from_handle(userdata)
659        widget.process_event(evt)
660
661Some other libraries don't have an explicit ``void *`` argument, but
662let you attach the ``void *`` to an existing structure.  For example,
663the library might say that ``widget->userdata`` is a generic field
664reserved for the application.  If the event's signature is now this::
665
666    typedef void (*event_cb_t)(widget_t *w, event_t *evt);
667
668Then you can use the ``void *`` field in the low-level
669``widget_t *`` like this::
670
671    from _demo_cffi import ffi, lib
672
673    class Widget(object):
674        def __init__(self):
675            ll_widget = lib.new_widget(500, 500)
676            self.ll_widget = ll_widget       # <cdata 'struct widget *'>
677            userdata = ffi.new_handle(self)
678            self._userdata = userdata        # must still keep this alive!
679            ll_widget.userdata = userdata    # this makes a copy of the "void *"
680            lib.event_cb_register(ll_widget, lib.my_event_callback)
681
682        def process_event(self, evt):
683            print "got event!"
684
685    @ffi.def_extern()
686    def my_event_callback(ll_widget, evt):
687        widget = ffi.from_handle(ll_widget.userdata)
688        widget.process_event(evt)
689
690Extern "Python" accessed from C directly
691~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
692
693In case you want to access some ``extern "Python"`` function directly
694from the C code written in ``set_source()``, you need to write a
695forward declaration.  (By default it needs to be static, but see
696`next paragraph`__.)  The real implementation of this function
697is added by CFFI *after* the C code---this is needed because the
698declaration might use types defined by ``set_source()``
699(e.g. ``event_t`` above, from the ``#include``), so it cannot be
700generated before.
701
702.. __: `extern-python-c`_
703
704::
705
706    ffibuilder.set_source("_demo_cffi", r"""
707        #include <the_event_library.h>
708
709        static void my_event_callback(widget_t *, event_t *);
710
711        /* here you can write C code which uses '&my_event_callback' */
712    """)
713
714This can also be used to write custom C code which calls Python
715directly.  Here is an example (inefficient in this case, but might be
716useful if the logic in ``my_algo()`` is much more complex)::
717
718    ffibuilder.cdef("""
719        extern "Python" int f(int);
720        int my_algo(int);
721    """)
722    ffibuilder.set_source("_example_cffi", r"""
723        static int f(int);   /* the forward declaration */
724
725        static int my_algo(int n) {
726            int i, sum = 0;
727            for (i = 0; i < n; i++)
728                sum += f(i);     /* call f() here */
729            return sum;
730        }
731    """)
732
733.. _extern-python-c:
734
735Extern "Python+C"
736~~~~~~~~~~~~~~~~~
737
738Functions declared with ``extern "Python"`` are generated as
739``static`` functions in the C source.  However, in some cases it is
740convenient to make them non-static, typically when you want to make
741them directly callable from other C source files.  To do that, you can
742say ``extern "Python+C"`` instead of just ``extern "Python"``.  *New
743in version 1.6.*
744
745+------------------------------------+--------------------------------------+
746| if the cdef contains               | then CFFI generates                  |
747+------------------------------------+--------------------------------------+
748| ``extern "Python" int f(int);``    | ``static int f(int) { /* code */ }`` |
749+------------------------------------+--------------------------------------+
750| ``extern "Python+C" int f(int);``  | ``int f(int) { /* code */ }``        |
751+------------------------------------+--------------------------------------+
752
753The name ``extern "Python+C"`` comes from the fact that we want an
754extern function in both senses: as an ``extern "Python"``, and as a
755C function that is not static.
756
757You cannot make CFFI generate additional macros or other
758compiler-specific stuff like the GCC ``__attribute__``.  You can only
759control whether the function should be ``static`` or not.  But often,
760these attributes must be written alongside the function *header*, and
761it is fine if the function *implementation* does not repeat them::
762
763    ffibuilder.cdef("""
764        extern "Python+C" int f(int);      /* not static */
765    """)
766    ffibuilder.set_source("_example_cffi", r"""
767        /* the forward declaration, setting a gcc attribute
768           (this line could also be in some .h file, to be included
769           both here and in the other C files of the project) */
770        int f(int) __attribute__((visibility("hidden")));
771    """)
772
773
774Extern "Python": reference
775~~~~~~~~~~~~~~~~~~~~~~~~~~
776
777``extern "Python"`` must appear in the cdef().  Like the C++ ``extern
778"C"`` syntax, it can also be used with braces around a group of
779functions::
780
781    extern "Python" {
782        int foo(int);
783        int bar(int);
784    }
785
786The ``extern "Python"`` functions cannot be variadic for now.  This
787may be implemented in the future.  (`This demo`__ shows how to do it
788anyway, but it is a bit lengthy.)
789
790.. __: https://bitbucket.org/cffi/cffi/src/default/demo/extern_python_varargs.py
791
792Each corresponding Python callback function is defined with the
793``@ffi.def_extern()`` decorator.  Be careful when writing this
794function: if it raises an exception, or tries to return an object of
795the wrong type, then the exception cannot be propagated.  Instead, the
796exception is printed to stderr and the C-level callback is made to
797return a default value.  This can be controlled with ``error`` and
798``onerror``, described below.
799
800.. _def-extern:
801
802The ``@ffi.def_extern()`` decorator takes these optional arguments:
803
804* ``name``: the name of the function as written in the cdef.  By default
805  it is taken from the name of the Python function you decorate.
806
807.. _error_onerror:
808
809* ``error``: the returned value in case the Python function raises an
810  exception.  It is 0 or null by default.  The exception is still
811  printed to stderr, so this should be used only as a last-resort
812  solution.
813
814* ``onerror``: if you want to be sure to catch all exceptions, use
815  ``@ffi.def_extern(onerror=my_handler)``.  If an exception occurs and
816  ``onerror`` is specified, then ``onerror(exception, exc_value,
817  traceback)`` is called.  This is useful in some situations where you
818  cannot simply write ``try: except:`` in the main callback function,
819  because it might not catch exceptions raised by signal handlers: if
820  a signal occurs while in C, the Python signal handler is called as
821  soon as possible, which is after entering the callback function but
822  *before* executing even the ``try:``.  If the signal handler raises,
823  we are not in the ``try: except:`` yet.
824
825  If ``onerror`` is called and returns normally, then it is assumed
826  that it handled the exception on its own and nothing is printed to
827  stderr.  If ``onerror`` raises, then both tracebacks are printed.
828  Finally, ``onerror`` can itself provide the result value of the
829  callback in C, but doesn't have to: if it simply returns None---or
830  if ``onerror`` itself fails---then the value of ``error`` will be
831  used, if any.
832
833  Note the following hack: in ``onerror``, you can access the original
834  callback arguments as follows.  First check if ``traceback`` is not
835  None (it is None e.g. if the whole function ran successfully but
836  there was an error converting the value returned: this occurs after
837  the call).  If ``traceback`` is not None, then
838  ``traceback.tb_frame`` is the frame of the outermost function,
839  i.e. directly the frame of the function decorated with
840  ``@ffi.def_extern()``.  So you can get the value of ``argname`` in
841  that frame by reading ``traceback.tb_frame.f_locals['argname']``.
842
843
844.. _Callbacks:
845
846Callbacks (old style)
847---------------------
848
849Here is how to make a new ``<cdata>`` object that contains a pointer
850to a function, where that function invokes back a Python function of
851your choice::
852
853    >>> @ffi.callback("int(int, int)")
854    >>> def myfunc(x, y):
855    ...    return x + y
856    ...
857    >>> myfunc
858    <cdata 'int(*)(int, int)' calling <function myfunc at 0xf757bbc4>>
859
860Note that ``"int(*)(int, int)"`` is a C *function pointer* type, whereas
861``"int(int, int)"`` is a C *function* type.  Either can be specified to
862ffi.callback() and the result is the same.
863
864.. warning::
865
866    Callbacks are provided for the ABI mode or for backward
867    compatibility.  If you are using the out-of-line API mode, it is
868    recommended to use the `extern "Python"`_ mechanism instead of
869    callbacks: it gives faster and cleaner code.  It also avoids several
870    issues with old-style callbacks:
871
872    - On less common architecture, libffi is more likely to crash on
873      callbacks (`e.g. on NetBSD`__);
874
875    - On hardened systems like PAX and SELinux, the extra memory
876      protections can interfere (for example, on SELinux you need to
877      run with ``deny_execmem`` set to ``off``).
878
879    Note also that a cffi fix for the latter issue was attempted---see
880    the ``ffi_closure_alloc`` branch---but was not merged because it
881    creates potential `memory corruption`__ with ``fork()``.
882
883.. __: https://github.com/pyca/pyopenssl/issues/596
884.. __: https://bugzilla.redhat.com/show_bug.cgi?id=1249685
885
886Warning: like ffi.new(), ffi.callback() returns a cdata that has
887ownership of its C data.  (In this case, the necessary C data contains
888the libffi data structures to do a callback.)  This means that the
889callback can only be invoked as long as this cdata object is alive.
890If you store the function pointer into C code, then make sure you also
891keep this object alive for as long as the callback may be invoked.
892The easiest way to do that is to always use ``@ffi.callback()`` at
893module-level only, and to pass "context" information around with
894`ffi.new_handle()`__, if possible.  Example:
895
896.. __: ref.html#new-handle
897
898.. code-block:: python
899
900    # a good way to use this decorator is once at global level
901    @ffi.callback("int(int, void *)")
902    def my_global_callback(x, handle):
903        return ffi.from_handle(handle).some_method(x)
904
905
906    class Foo(object):
907
908        def __init__(self):
909            handle = ffi.new_handle(self)
910            self._handle = handle   # must be kept alive
911            lib.register_stuff_with_callback_and_voidp_arg(my_global_callback, handle)
912
913        def some_method(self, x):
914            print "method called!"
915
916(See also the section about `extern "Python"`_ above, where the same
917general style is used.)
918
919Note that callbacks of a variadic function type are not supported.  A
920workaround is to add custom C code.  In the following example, a
921callback gets a first argument that counts how many extra ``int``
922arguments are passed:
923
924.. code-block:: python
925
926    # file "example_build.py"
927
928    import cffi
929
930    ffibuilder = cffi.FFI()
931    ffibuilder.cdef("""
932        int (*python_callback)(int how_many, int *values);
933        void *const c_callback;   /* pass this const ptr to C routines */
934    """)
935    ffibuilder.set_source("_example", r"""
936        #include <stdarg.h>
937        #include <alloca.h>
938        static int (*python_callback)(int how_many, int *values);
939        static int c_callback(int how_many, ...) {
940            va_list ap;
941            /* collect the "..." arguments into the values[] array */
942            int i, *values = alloca(how_many * sizeof(int));
943            va_start(ap, how_many);
944            for (i=0; i<how_many; i++)
945                values[i] = va_arg(ap, int);
946            va_end(ap);
947            return python_callback(how_many, values);
948        }
949    """)
950    ffibuilder.compile(verbose=True)
951
952.. code-block:: python
953
954    # file "example.py"
955
956    from _example import ffi, lib
957
958    @ffi.callback("int(int, int *)")
959    def python_callback(how_many, values):
960        print ffi.unpack(values, how_many)
961        return 0
962    lib.python_callback = python_callback
963
964Deprecated: you can also use ``ffi.callback()`` not as a decorator but
965directly as ``ffi.callback("int(int, int)", myfunc)``.  This is
966discouraged: using this a style, we are more likely to forget the
967callback object too early, when it is still in use.
968
969The ``ffi.callback()`` decorator also accepts the optional argument
970``error``, and from CFFI version 1.2 the optional argument ``onerror``.
971These two work in the same way as `described above for extern "Python".`__
972
973.. __: error_onerror_
974
975
976
977Windows: calling conventions
978----------------------------
979
980On Win32, functions can have two main calling conventions: either
981"cdecl" (the default), or "stdcall" (also known as "WINAPI").  There
982are also other rare calling conventions, but these are not supported.
983*New in version 1.3.*
984
985When you issue calls from Python to C, the implementation is such that
986it works with any of these two main calling conventions; you don't
987have to specify it.  However, if you manipulate variables of type
988"function pointer" or declare callbacks, then the calling convention
989must be correct.  This is done by writing ``__cdecl`` or ``__stdcall``
990in the type, like in C::
991
992    @ffi.callback("int __stdcall(int, int)")
993    def AddNumbers(x, y):
994        return x + y
995
996or::
997
998    ffibuilder.cdef("""
999        struct foo_s {
1000            int (__stdcall *MyFuncPtr)(int, int);
1001        };
1002    """)
1003
1004``__cdecl`` is supported but is always the default so it can be left
1005out.  In the ``cdef()``, you can also use ``WINAPI`` as equivalent to
1006``__stdcall``.  As mentioned above, it is mostly not needed (but doesn't
1007hurt) to say ``WINAPI`` or ``__stdcall`` when declaring a plain
1008function in the ``cdef()``.  (The difference can still be seen if you
1009take explicitly a pointer to this function with ``ffi.addressof()``,
1010or if the function is ``extern "Python"``.)
1011
1012These calling convention specifiers are accepted but ignored on any
1013platform other than 32-bit Windows.
1014
1015In CFFI versions before 1.3, the calling convention specifiers are not
1016recognized.  In API mode, you could work around it by using an
1017indirection, like in the example in the section about Callbacks_
1018(``"example_build.py"``).  There was no way to use stdcall callbacks
1019in ABI mode.
1020
1021
1022FFI Interface
1023-------------
1024
1025(The reference for the FFI interface has been moved to the `next page`__.)
1026
1027.. __: ref.html
1028