Debian Codegraph @

doc/source/cffi-gen-src.rst

raw
1 .. _cffi_gen_src_docs:
2
3 ========================================
4 Generating C Sources for CFFI Extensions
5 ========================================
6
7 .. contents::
8
9 CFFI ships a command-line tool, ``cffi-gen-src``, that produces the
10 same output as :meth:`FFI.emit_c_code`: a ``.c`` source file ready to
11 be compiled into a CPython c-extension module. This is useful for
12 projects that want CFFI to generate source code for a later compilation
13 step without depending on setuptools.
14
15 Installing CFFI installs the ``cffi-gen-src`` script; running ``python
16 -m cffi.gen_src`` invokes the same command line and behaves
17 identically. Use the former where a script with a Python shebang
18 makes more sense (e.g. cross-compiling) and use the latter when the
19 console script is not on PATH but a Python interpreter is.
20
21 In a packaged project, ``cffi-gen-src`` is usually called by a script or
22 rule executed by a build backend, and the build backend then consumes the
23 generated C file. Any `Python build backend`_ that can run a source generator,
24 such as
25 `meson-python <https://meson-python.readthedocs.io/>`_,
26 `scikit-build-core <https://scikit-build-core.readthedocs.io/>`_, or
27 similar, can use ``cffi-gen-src`` the same way. The rest of this page uses
28 meson-python in the examples.
29
30 The command line is the only supported interface; the Python API inside
31 ``cffi._cffi_gen_src`` is private.
32
33 The implementation is based on the `cffi-buildtool`_ project by Rose Davidson
34 (`@inklesspen`_ on GitHub). It is included in CFFI with permission of the original
35 author.
36
37 .. _Python build backend: https://packaging.python.org/en/latest/guides/tool-recommendations/#build-backends-for-extension-modules
38 .. _cffi-buildtool: https://github.com/inklesspen/cffi-buildtool
39 .. _@inklesspen: https://github.com/inklesspen
40
41 The ``cffi-gen-src`` Command-line Tool
42 ======================================
43
44 ``cffi-gen-src`` has two subcommands. The first, ``exec-python`` is
45 most useful if you already have a Python script that sets up an FFI
46 definition. The second, ``read-sources`` is most useful if you are wrapping
47 a large API surface and want a more structured way to specify a set of FFI
48 definitions.
49
50 ``cffi-gen-src exec-python``
51 ----------------------------
52
53 This mode executes a Python script that creates a :class:`cffi.FFI` object
54 as a module-level global and calls :meth:`FFI.set_source` on it, then emits
55 the generated C source. By default ``cffi-gen-src`` looks for a global
56 named ``ffibuilder``; pass ``--ffi-var`` if the object has another name.
57 Apart from being run by the tool instead of by hand, it is the same script
58 the CFFI docs show under :ref:`real-example`.
59
60 Let's say we want to create an extension module that wraps a single C function named
61 ``square``. The ``square`` function has the following signature:
62
63 .. code-block:: C
64
65 int square(int n);
66
67 Let's also say this function definition is exposed inside a header named
68 `square.h`. We could create a set of FFI bindings for this function given this
69 ``_squared_build.py``::
70
71 from cffi import FFI
72
73 ffibuilder = FFI()
74
75 ffibuilder.cdef("int square(int n);")
76
77 ffibuilder.set_source(
78 "squared._squared",
79 '#include "square.h"',
80 )
81
82 To generate the source code for the C extension, you would run:
83
84 .. code-block:: console
85
86 $ cffi-gen-src exec-python _squared_build.py _squared.c
87
88 Many CFFI FFI definition scripts have an ``if __name__ == "__main__"`` section
89 that triggers a compilation step. This is not needed for a script run
90 by ``cffi-gen-src``, which only writes the generated C source. If the
91 script does have such a section it is harmless: the script is executed with
92 ``__name__`` set to
93 ``"cffi.gen_src"``, so the block is skipped and an existing FFI
94 definition script works unchanged.
95
96 If the :class:`cffi.FFI` is bound to a name other than ``ffibuilder``, pass
97 ``--ffi-var``. To make that concrete, let's say your FFI definition script
98 creates an FFI object named ``make_ffi``::
99
100 from cffi import FFI
101
102 make_ffi = FFI()
103
104 In that case, you would pass ``--ffi-var=make_ffi`` to ``cffi-gen-src``:
105
106 .. code-block:: console
107
108 $ cffi-gen-src exec-python --ffi-var=make_ffi _squared_build.py _squared.c
109
110 .. note::
111
112 ``cffi-gen-src`` emits C source for out-of-line API mode modules. It
113 cannot emit source for ABI mode modules where :meth:`FFI.set_source`
114 is called with ``None``.
115
116 .. note::
117
118 CFFI's setuptools integration supports passing ``libraries=``,
119 ``library_dirs=``, ``include_dirs=``, and ``extra_compile_args=``
120 arguments to :meth:`FFI.set_source`. When using ``cffi-gen-src``,
121 these arguments are *ignored*. Link and include settings are the
122 responsibility of the compilation step that happens after generating
123 the C extension sources. If you are using meson-python following the
124 examples in this section, you would express them through the
125 ``dependencies``, ``include_directories``, and ``c_args`` arguments of
126 ``py.extension_module()``.
127
128 ``cffi-gen-src read-sources``
129 -----------------------------
130
131 For larger modules, keeping the FFI definition and any necessary C
132 source prelude in separate files tends to be easier to work with --
133 you can configure your editor to treat them as plain C, and write
134 presubmit tooling that parses the FFI definition directly without
135 extracting it from a Python script.
136
137 Given ``squared.cdef.txt``:
138
139 .. code-block:: C
140
141 int square(int n);
142
143 and ``squared.csrc.c``:
144
145 .. code-block:: C
146
147 #include "square.h"
148
149 you would run the following command to generate the C source code for a CFFI extension:
150
151 .. code-block:: console
152
153 $ cffi-gen-src read-sources squared._squared squared.cdef.txt squared.csrc.c _squared.c
154
155 With all other details left exactly the same as the ``exec-python`` example.
156
157 The first positional argument passed to the ``read-sources`` command is the
158 fully qualified module name that will be embedded in the generated C source
159 code (equivalent to the first argument to :meth:`FFI.set_source`).
160
161
162 A Worked Example Using ``meson-python``
163 =======================================
164
165 Project layout:
166
167 .. code-block:: text
168
169 squared/
170 ├── pyproject.toml
171 ├── meson.build
172 └── src/
173 ├── squared/
174 │ ├── __init__.py
175 │ └── _squared_build.py
176 └── csrc/
177 ├── square.h
178 └── square.c
179
180 ``pyproject.toml``:
181
182 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/exec_python_example/pyproject.toml
183 :language: toml
184
185 ``meson.build``:
186
187 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/exec_python_example/meson.build
188 :language: meson
189
190 ``src/squared/__init__.py``:
191
192 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/exec_python_example/src/squared/__init__.py
193 :language: python
194
195 ``src/squared/_squared_build.py``:
196
197 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/exec_python_example/src/squared/_squared_build.py
198 :language: python
199
200 ``src/csrc/square.h``:
201
202 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/exec_python_example/src/csrc/square.h
203 :language: C
204
205 ``src/csrc/square.c``:
206
207 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/exec_python_example/src/csrc/square.c
208 :language: C
209
210 Build and install the project with any Python build front-end. For
211 example, with `pip`, in the root `squared` directory:
212
213 .. code-block:: console
214
215 $ python -m pip install .
216 $ python -c "from squared import squared; print(squared(7))"
217 49
218
219 To switch this project to ``read-sources`` mode, replace
220 ``_squared_build.py`` with two files, so that the project layout
221 becomes:
222
223 .. code-block:: text
224
225 squared/
226 ├── pyproject.toml
227 ├── meson.build
228 └── src/
229 ├── squared/
230 │ ├── __init__.py
231 │ ├── squared.cdef.txt
232 │ └── squared.csrc.c
233 └── csrc/
234 ├── square.h
235 └── square.c
236
237 The first new file, ``squared.cdef.txt``, contains the FFI definition:
238
239 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/read_sources_example/src/squared/squared.cdef.txt
240 :language: python
241
242 and the second, ``squared.csrc.c``, contains the C source prelude:
243
244 .. literalinclude:: ../../testing/cffi1/cffi_gen_src_examples/read_sources_example/src/squared/squared.csrc.c
245 :language: python
246
247 then change two spots in the ``meson.build`` file. First, update the ``custom_target``
248 ``command`` to call ``cffi-gen-src read-sources`` with two input arguments:
249
250 .. code-block:: meson
251
252 command: [
253 cffi_gen_src,
254 'read-sources',
255 'squared._squared',
256 '@INPUT0@',
257 '@INPUT1@',
258 '@OUTPUT@',
259 ],
260
261 and then list both of the FFI specification files under ``input``:
262
263 .. code-block:: meson
264
265 input: ['src/squared/squared.cdef.txt', 'src/squared/squared.csrc.c']
266
267 Distributing CFFI Extensions using Setuptools
268 =============================================
269
270 .. _distutils-setuptools:
271
272 You can (but don't have to) use CFFI's **Distutils** or
273 **Setuptools integration** when writing a ``setup.py``. For
274 Distutils (only in out-of-line API mode; deprecated since
275 Python 3.10):
276
277 .. code-block:: python
278
279 # setup.py (requires CFFI to be installed first)
280 from distutils.core import setup
281
282 import foo_build # possibly with sys.path tricks to find it
283
284 setup(
285 ...,
286 ext_modules=[foo_build.ffibuilder.distutils_extension()],
287 )
288
289 For Setuptools (out-of-line only, but works in ABI or API mode;
290 recommended):
291
292 .. code-block:: python
293
294 # setup.py (with automatic dependency tracking)
295 from setuptools import setup
296
297 setup(
298 ...,
299 setup_requires=["cffi>=1.0.0"],
300 cffi_modules=["package/foo_build.py:ffibuilder"],
301 install_requires=["cffi>=1.0.0"],
302 )
303
304 Note again that the ``foo_build.py`` example contains the following
305 lines, which mean that the ``ffibuilder`` is not actually compiled
306 when ``package.foo_build`` is merely imported---it will be compiled
307 independently by the Setuptools logic, using compilation parameters
308 provided by Setuptools:
309
310 .. code-block:: python
311
312 if __name__ == "__main__": # not when running with setuptools
313 ffibuilder.compile(verbose=True)
314
315 * Note that some bundler tools that try to find all modules used by a
316 project, like PyInstaller, will miss ``_cffi_backend`` in the
317 out-of-line mode because your program contains no explicit ``import
318 cffi`` or ``import _cffi_backend``. You need to add
319 ``_cffi_backend`` explicitly (as a "hidden import" in PyInstaller,
320 but it can also be done more generally by adding the line ``import
321 _cffi_backend`` in your main program).
322
323 Note that CFFI actually contains two different ``FFI`` classes. The
324 page `Using the ffi/lib objects`_ describes the common functionality.
325 It is what you get in the ``from package._foo import ffi`` lines above.
326 On the other hand, the extended ``FFI`` class is the one you get from
327 ``import cffi; ffi_or_ffibuilder = cffi.FFI()``. It has the same
328 functionality (for in-line use), but also the extra methods described
329 below (to prepare the FFI). NOTE: We use the name ``ffibuilder``
330 instead of ``ffi`` in the out-of-line context, when the code is about
331 producing a ``_foo.so`` file; this is an attempt to distinguish it
332 from the different ``ffi`` object that you get by later saying
333 ``from _foo import ffi``.
334
335 .. _`Using the ffi/lib objects`: using.html
336
337 The reason for this split of functionality is that a regular program
338 using CFFI out-of-line does not need to import the ``cffi`` pure
339 Python package at all. (Internally it still needs ``_cffi_backend``,
340 a C extension module that comes with CFFI; this is why CFFI is also
341 listed in ``install_requires=..`` above. In the future this might be
342 split into a different PyPI package that only installs
343 ``_cffi_backend``.)
344
345 Note that a few small differences do exist: notably, ``from _foo import
346 ffi`` returns an object of a type written in C, which does not let you
347 add random attributes to it (nor does it have all the
348 underscore-prefixed internal attributes of the Python version).
349 Similarly, the ``lib`` objects returned by the C version are read-only,
350 apart from writes to global variables. Also, ``lib.__dict__`` does
351 not work before version 1.2 or if ``lib`` happens to declare a name
352 called ``__dict__`` (use instead ``dir(lib)``). The same is true
353 for ``lib.__class__``, ``lib.__all__`` and ``lib.__name__`` added
354 in successive versions.