Debian Codegraph @

rpython/doc/rffi.rst

raw
1 .. _rffi:
2
3 Foreign Function Interface for RPython
4 ======================================
5
6 Purpose
7 -------
8
9 This document describes an FFI for the RPython language, concentrating
10 on low-level backends like C. It describes
11 how to declare and call low-level (C) functions from RPython level.
12
13
14 Declaring low-level external function
15 -------------------------------------
16
17 Declaring external C function in RPython is easy, but one needs to
18 remember that low level functions eat :ref:`low level types <low-level-types>` (like
19 lltype.Signed or lltype.Array) and memory management must be done
20 by hand. To declare a function, we write::
21
22 from rpython.rtyper.lltypesystem import rffi
23
24 external_function = rffi.llexternal(name, args, result)
25
26 where:
27
28 * name - a C-level name of a function (how it would be rendered)
29 * args - low level types of args
30 * result - low level type of a result
31
32 You can pass in additional information about C-level includes,
33 libraries and sources by passing in the optional ``compilation_info``
34 parameter::
35
36 from rpython.rtyper.lltypesystem import rffi
37 from rpython.translator.tool.cbuild import ExternalCompilationInfo
38
39 info = ExternalCompilationInfo(includes=[], libraries=[])
40
41 external_function = rffi.llexternal(
42 name, args, result, compilation_info=info
43 )
44
45 See :source:`cbuild <rpython/translator/tool/cbuild.py>` for more info on ExternalCompilationInfo.
46
47
48 Types
49 -----
50
51 In :source:`rffi <rpython/rtyper/lltypesystem/rffi.py>` there are various declared types for C-structures, like CCHARP
52 (char*), SIZE_T (size_t) and others. Refer to file for details.
53 Instances of non-primitive types must be alloced by hand, with call
54 to lltype.malloc, and freed by lltype.free both with keyword argument
55 flavor='raw'. There are several helpers like string -> char*
56 converter, refer to the source for details.
57
58
59 Registering function as external
60 --------------------------------
61
62 Once we provided low-level implementation of an external function,
63 would be nice to wrap call to some library function (like os.open)
64 with such a call. For this, there is a `register_external` routine,
65 located in :source:`extfunc.py <rpython/rtyper/extfunc.py>`, which provides nice API for declaring such a
66 functions, passing llimpl as an argument and eventually llfakeimpl
67 as a fake low-level implementation for tests performed by an llinterp.