Debian Codegraph @

src/doc/old-manual/ffi.xmlf

raw
1 <?xml version="1.0" encoding="utf-8"?>
2 <!DOCTYPE book [
3 <!ENTITY % eclent SYSTEM "ecl.ent">
4 %eclent;
5 ]>
6 <book xmlns="http://docbook.org/ns/docbook" version="5.0" xml:lang="en">
7 <chapter xml:id="ext.ffi">
8 <title>Foreign Function Interface</title>
9
10 <section xml:id="ext.ffi.what">
11 <title>What is a FFI?</title>
12
13 <para>A Foreign Function Interface, or &FFI; for short, is a means for a
14 programming language to interface with libraries written in other programming
15 languages, the <emphasis>foreign code</emphasis>. You will see this concept
16 most often being used in interpreted environments, such as Python, Ruby or
17 Lisp, where one wants to reuse the big number of libraries written in C
18 and C++ for dealing with graphical interfaces, networking, filesystems,
19 etc.</para>
20
21 <para>A FFI is made of at least three components:</para>
22 <variablelist>
23 <varlistentry>
24 <term>Foreign objects management</term>
25 <listitem><para>This is the data that the foreign code will use. A &FFI;
26 needs to provide means to build and manipulate foreign data, with automatic
27 conversions to and from lisp data types whenever possible, and it also has
28 to deal with issues like garbage collection and
29 finalization.</para></listitem>
30 </varlistentry>
31 <varlistentry>
32 <term>Foreign code loader</term>
33 <listitem><para>To actually use a foreign routine, the code must reside in
34 memory. The process of loading this code and finding out the addresses of
35 the routines we want to use is normally done by an independent
36 component.</para></listitem>
37 </varlistentry>
38 <varlistentry>
39 <term>Foreign function invocation</term>
40 <listitem><para>This is the part of the &FFI; that deals with actually
41 calling the foreign routines we want to use. For that one typically has to
42 tell the &FFI; what are the arguments that these routines expect, what are
43 the calling conventions and where are these routines to be
44 found.</para></listitem>
45 </varlistentry>
46 </variablelist>
47
48 <para>On top of these components sits a higher level interface written
49 entirely in lisp, with which you will actually declare and use foreign
50 variables, functions and libraries. In the following sections we describe
51 both the details of the low-level components (<xref linkend="ext.ffi.dffi"/>,
52 <xref linkend="ext.ffi.objects"/>), and of the higher level interface (<xref
53 linkend="ext.ffi.uffi.and.cffi"/>). It is highly recommended that you read
54 <emphasis>all</emphasis> sections.</para>
55 </section>
56
57 <section xml:id="ext.ffi.dffi">
58 <title>Two kinds of FFI</title>
59
60 <para>&ECL; allows for two different appraoches when building a &FFI;. Both
61 approaches have a different implementation philosophy and affect the places
62 where you can use the &FFI; and how.
63 <variablelist>
64 <varlistentry>
65 <term>Static &FFI;</term>
66 <listitem><para>For every foreign function and variable you might need to
67 use, a wrapper is automatically written in C with the help of <xref
68 linkend="ref.c-inline"/>. These wrappers are compiled using an ordinary C
69 compiler and linked against both the foreign libraries you want to use and
70 against the &ECL; library. The result is a &FASL; file that can be loaded
71 from &ECL; and where the wrappers appear as ordinary lisp functions and
72 variables that the user may directly invoked.</para></listitem>
73 </varlistentry>
74 <varlistentry>
75 <term>Dynamic &FFI;</term>
76 <listitem><para>First of all, the foreign libraries are loaded in memory
77 using the facilities of the operating system. Similar routines are used to
78 find out and register the memory location of all the functions and
79 variables we want to use. Finally, when actually accessing these functions,
80 a little piece of assembly code does the job of translating the lisp data
81 into foreign objects, storing the arguments in the stack and in CPU
82 registers, calling the function and converting back the output of the
83 function to lisp.</para>
84
85 <para>&ECL; for this purpose utilizes the library "A Portable Foreign
86 Function Interface Library" commonly known as <ulink
87 url="https://sourceware.org/libffi/">libffi</ulink>.</para></listitem>
88 </varlistentry>
89 <!-- XXX: describe also DLOPEN interface, it's the 3rd option (!) -->
90 </variablelist>
91 </para>
92
93 <para>
94 <figure float="1" xml:id="fig.ffi">
95 <title>FFI components</title>
96 <mediaobject>
97 <imageobject>
98 <imagedata align="center" fileref="figures/ffi.png"
99 format="PNG" width="300px"/>
100 </imageobject>
101 </mediaobject>
102 </figure>As you see, the first approach uses rather portable technices based
103 on a programming language (C, C++) which is strongly supported by the
104 operating system. The conversion of data is performed calling routines in the
105 &ECL; library and we need not care about the precise details (organizing the
106 stack, CPU registers, etc) when calling a function: the compiler does this
107 for us.</para>
108
109 <para>On the other hand, the dynamic approach allows us to choose the
110 libraries we load at any time, look for the functions and invoke them even
111 from the toplevel, but it relies on unportable techniques and requires the
112 developers to know very well both the assembly code of the machine the code
113 runs on and the calling conventions of that particular operating system. For
114 these reasons &ECL; doesn't maintain it's own implementation of the DFFI but
115 rather relies on the third party library.</para>
116
117 <para>&ECL; currently supports the static method on all platforms, and the
118 dynamical one a wide range of the most popular ones, shown in <ulink
119 url="https://sourceware.org/libffi/">libffi</ulink>. You can test if your
120 copy of &ECL; was built with DFFI by inspecting whether the symbol
121 <symbol>:DFFI</symbol> is present in the list from variable
122 <symbol>*FEATURES*</symbol>.</para>
123
124 </section>
125
126 <section xml:id="ext.ffi.objects">
127 <title>Foreign objects</title>
128
129 <para>While the foreign function invocation protocols differ strongly between
130 platforms and implementations, foreign objects are pretty easy to handle
131 portably. For &ECL;, a foreign object is just a bunch of bytes stored in
132 memory. The lisp object for a foreign object encapsulates several bits of
133 information:
134 <itemizedlist>
135 <listitem><para>A list or a symbol specifying the C type of the
136 object.</para></listitem>
137 <listitem><para>The pointer to the region of memory where data is
138 stored.</para></listitem>
139 <listitem><para>A flag determining whether &ECL; can automatically manage
140 that piece of memory and deallocated when no longer in
141 use.</para></listitem>
142 </itemizedlist></para>
143
144 <para>A foreign object may contain many different kinds of data: integers,
145 floating point numbers, C structures, unions, etc. The actual type of the
146 object is stored in a list or a symbol which is understood by the higher
147 level interface (<xref linkend="ext.ffi.uffi.and.cffi"/>).</para>
148
149 <para>The most important component of the object is the memory region where
150 data is stored. By default &ECL; assumes that the user will perform automatic
151 management of this memory, deleting the object when it is no longer
152 needed. The first reason is that this block may have been allocated by a
153 foreign routine using <function>malloc()</function>, or
154 <function>mmap()</function>, or statically, by referring to a C constant. The
155 second reason is that foreign functions may store references to this memory
156 which &ECL; is not aware of and, in order to keep these references valid,
157 &ECL; should not attempt to automatically destroy the object.</para>
158
159 <para>In many cases, however, it is desirable to automatically destroy
160 foreign objects once they have been used. The higher level interfaces &UFFI;
161 and &CFFI; provide tools for doing this. For instance, in the following
162 example adapted from the &UFFI; documentation, the string
163 <varname>NAME</varname> is automatically deallocated</para>
164 <programlisting>(def-function "gethostname"
165 ((name (* :unsigned-char))
166 (len :int))
167 :returning :int)
168
169 (if (zerop (c-gethostname (ffi:char-array-to-pointer name) 256))
170 (format t "Hostname: ~S" (ffi:convert-from-foreign-string name))
171 (error "gethostname() failed."))
172 </programlisting>
173 </section>
174
175 <section xml:id="ext.ffi.uffi.and.cffi">
176 <title>Higher level interfaces</title>
177
178 <para>Up to now we have only discussed vague ideas about how a &FFI; works,
179 but you are probably more interested on how to actually code all these things
180 in lisp. You have here three possibilities:</para>
181 <itemizedlist>
182 <listitem>
183 <para>&ECL; supplies a high level interface which is compatible with &UFFI;
184 up to version 1.8 (api for >=v2.0 is provided by
185 <symbol>cffi-uffi-compat</symbol> system shipped with &CFFI;). Code
186 designed for &UFFI; library should run mostly unchanged with &ECL;. Note,
187 that api resides in <symbol>ffi</symbol> package, not
188 <symbol>uffi</symbol>, to prevent conflicts with
189 <symbol>cffi-uffi-compat</symbol>.</para>
190 </listitem>
191 <listitem>
192 <para>The &CFFI; library features a mostly complete backend for &ECL;. This
193 is however a work in progress, as the fact that &CFFI; allows for calling
194 arbitrary functions without declaring them causes some troubles with
195 &ECL;.</para>
196 </listitem>
197 <listitem>
198 <para>&ECL;'s own low level interface. Only to be used if &ECL; is your
199 deployment platform. It features some powerful constructs that allow you to
200 mix arbitrary C code with lisp (<xref linkend="ref.c-inline"/> and <xref
201 linkend="ref.clines"/>).</para>
202 </listitem>
203 </itemizedlist>
204
205 <para>In the following two subsections we will discuss two practical examples
206 of using the native &UFFI; and the &CFFI; library.</para>
207
208 <section xml:id="ext.ffi.uffi-example">
209 <title>UFFI example</title>
210
211 <para>The example below shows how to use &UFFI; in an application. There are
212 several important ingredients:
213 <itemizedlist>
214 <listitem><para>You need to specify the libraries you use and do it at the
215 toplevel, so that the compiler may include them at link
216 time.</para></listitem>
217 <listitem><para>Every function you will use has to be declared using
218 <function>ffi:def-function</function>.</para></listitem>
219 </itemizedlist>
220 </para>
221 <programlisting>
222 #|
223 Build and load this module with (compile-file "uffi.lsp" :load t)
224 |#
225 ;;
226 ;; This toplevel statement notifies the compiler that we will
227 ;; need this shared library at runtime. We do not need this
228 ;; statement in windows.
229 ;;
230 #-(or ming32 windows)
231 (ffi:load-foreign-library #+darwin "/usr/lib/libm.dylib"
232 #-darwin "/usr/lib/libm.so")
233 ;;
234 ;; With this other statement, we import the C function sin(),
235 ;; which operates on IEEE doubles.
236 ;;
237 (ffi:def-function ("sin" c-sin) ((arg :double))
238 :returning :double)
239 ;;
240 ;; We now use this function and compare with the lisp version.
241 ;;
242 (format t "~%Lisp sin:~t~d~%C sin:~t~d~%Difference:~t~d"
243 (sin 1.0d0) (c-sin 1.0d0) (- (sin 1.0d0) (c-sin 1.0d0)))
244 </programlisting>
245 </section>
246
247 <section xml:id="ext.ffi.cffi-example">
248 <title>CFFI example</title>
249
250 <para>The &CFFI; library is an independent project and it is not shipped
251 with &ECL;. If you wish to use it you can go to their <ulink
252 url="https://www.common-lisp.net/project/cffi/">homepage</ulink>, download
253 the code and build it using &ASDF;.</para>
254
255 <para>&CFFI; differs slightly from &UFFI; in that functions may be used even
256 without being declared beforehand. This poses a few problems to the &ECL;
257 backend, but hopefully these should have been solved in the latest
258 releases.</para>
259 <programlisting>
260 #|
261 Build and load this module with (compile-file "cffi.lsp" :load t)
262 |#
263 ;;
264 ;; This toplevel statement notifies the compiler that we will
265 ;; need this shared library at runtime. We do not need this
266 ;; statement in windows.
267 ;;
268 #-(or ming32 windows)
269 (cffi:load-foreign-library #+darwin "/usr/lib/libm.dylib"
270 #-darwin "/usr/lib/libm.so")
271 ;;
272 ;; With this other statement, we import the C function sin(),
273 ;; which operates on IEEE doubles.
274 ;;
275 (cffi:defcfun ("sin" c-sin) :double '(:double))
276 ;;
277 ;; We now use this function and compare with the lisp version.
278 ;;
279 (format t "~%Lisp sin:~t~d~%C sin:~t~d~%Difference:~t~d"
280 (sin 1.0d0) (c-sin 1.0d0) (- (sin 1.0d0) (c-sin 1.0d0)))
281 ;;
282 ;; The following also works: no declaration!
283 ;;
284 (let ((c-cos (cffi:foreign-funcall "cos" :double 1.0d0 :double)))
285 (format t "~%Lisp cos:~t~d~%C cos:~t~d~%Difference:~t~d"
286 (cos 1.0d0) c-cos (- (cos 1.0d0) c-cos)))
287 </programlisting>
288 </section>
289
290 <section xml:id="ext.ffi.ecl-example">
291 <title>Low level example</title>
292
293 <para>To compare with the previous pieces of code, we show how the previous
294 programs would be written using <xref linkend="ref.clines"/> and <xref
295 linkend="ref.c-inline"/></para>
296 <programlisting>
297 #|
298 Build and load this module with (compile-file "ecl.lsp" :load t)
299 |#
300 ;;
301 ;; With this other statement, we import the C function sin(), which
302 ;; operates on IEEE doubles. Notice that we include the C header to
303 ;; get the full declaration.
304 ;;
305 (defun c-sin (x)
306 (ffi:clines "#include &lt;math.h&gt;")
307 (ffi:c-inline (x) (:double) :double "sin(#0)" :one-liner t))
308 ;;
309 ;; We now use this function and compare with the lisp version.
310 ;;
311 (format t "~%Lisp sin:~t~d~%C sin:~t~d~%Difference:~t~d"
312 (sin 1.0d0) (c-sin 1.0d0) (- (sin 1.0d0) (c-sin 1.0d0)))
313 </programlisting>
314 </section>
315 </section>
316
317 <section xml:id="ext.ffi.dict">
318 <title>FFI Reference</title>
319 <toc/>
320
321 <!-- ====================================================================== -->
322 <!-- FFI:CLINES -->
323 <!-- ====================================================================== -->
324
325 <refentry xml:id="ref.clines">
326 <refnamediv>
327 <refname><function>ffi:clines</function></refname>
328 <refpurpose>Insert C declarations and definitions</refpurpose>
329 </refnamediv>
330
331 <refsynopsisdiv>
332 <title>Special form</title>
333 <funcsynopsis>
334 <funcprototype>
335 <funcdef>ffi:clines</funcdef>
336 <paramdef><parameter>c-code</parameter>*</paramdef>
337 </funcprototype>
338 </funcsynopsis>
339 <simplelist columns="2" type="horiz">
340 <member><replaceable>c-code</replaceable></member>
341 <member>One or more strings with C definitions. Not evaluated.</member>
342
343 <member>returns</member>
344 <member>No value.</member>
345 </simplelist>
346 </refsynopsisdiv>
347
348 <refsect1>
349 <title>Description</title>
350
351 <para>This special form inserts C code directly in the file that results
352 from compiling lisp sources. Contrary to <xref linkend="ref.c-inline"/>,
353 this function may have no executable statements, accepts no input value and
354 returnsn no value.</para>
355
356 <para>The main use of <function>FFI:CLINES</function> is to declare or
357 define C variables and functions that are going to be used later in other
358 &FFI; statements.</para>
359
360 <para><function>FFI:CLINES</function> is a special form that can only be
361 used in lisp compiled files as a toplevel form. Other uses will lead to an
362 error being signaled, either at compilation time or when loading the
363 file.</para>
364
365 </refsect1>
366 <refsect1>
367 <title>Examples</title>
368
369 <para>In this example the <function>FFI:CLINES</function> statement is
370 required to get access to the C function <function>cos()</function></para>
371 <programlisting>(ffi:clines "#include &lt;math.h&gt;")
372 (defun cos (x)
373 (ffi:c-inline (x) (:double) :double "cos(#0)" :on-liner t))</programlisting>
374
375 </refsect1>
376 </refentry>
377
378 <!-- ====================================================================== -->
379 <!-- FFI:C-INLINE -->
380 <!-- ====================================================================== -->
381
382 <refentry xml:id="ref.c-inline">
383 <refnamediv>
384 <refname><function>ffi:c-inline</function></refname>
385 <refpurpose>Inline C code in a lisp form.</refpurpose>
386 </refnamediv>
387
388 <refsynopsisdiv>
389 <title>Special form</title>
390 <funcsynopsis>
391 <funcprototype>
392 <funcdef>ffi:c-inline</funcdef>
393 <paramdef>(<parameter>lisp-value</parameter>*)</paramdef>
394 <paramdef>(<parameter>c-type</parameter>*)</paramdef>
395 <paramdef><parameter>return-type</parameter></paramdef>
396 <paramdef><parameter>C-code</parameter></paramdef>
397 <paramdef>&key;</paramdef>
398 <paramdef><parameter>one-liner</parameter></paramdef>
399 <paramdef><parameter>side-effects</parameter></paramdef>
400 </funcprototype>
401 </funcsynopsis>
402 <simplelist columns="2" type="horiz">
403 <member><replaceable>lisp-value</replaceable></member>
404 <member>A lisp expression, evaluated.</member>
405
406 <member><replaceable>c-type</replaceable></member>
407 <member>A valid <acronym>FFI</acronym> type.</member>
408
409 <member><replaceable>return-type</replaceable></member>
410 <member>A valid <acronym>FFI</acronym> type or <code>(VALUES)</code>.</member>
411
412 <member><replaceable>C-code</replaceable></member>
413 <member>A string with valid C code plus some valid escape forms.</member>
414
415 <member><replaceable>one-liner</replaceable></member>
416 <member>A boolean, defaults to <symbol>NIL</symbol>.</member>
417
418 <member><replaceable>side-effects</replaceable></member>
419 <member>A boolean, defaults to <symbol>T</symbol>.</member>
420
421 <member>returns</member>
422 <member>One or more lisp values.</member>
423 </simplelist>
424 </refsynopsisdiv>
425
426 <refsect1>
427 <title>Description</title>
428
429 <para>This is an special form which can be only used in compiled code and
430 whose purpose is to execute some C code getting and returning values from
431 and to the lisp environment.</para>
432
433 <para>The first argument to <function>ffi:c-inline</function> is a list of
434 lisp forms. These forms are going to be evaluated and their lisp values
435 will be transformed to the corresponding C types denoted by
436 <replaceable>c-type</replaceable>.</para>
437
438 <para>The input values are used to create a valid C expression using the
439 template in <replaceable>C-code</replaceable>. This is a string of
440 arbitrary size which mixes C expressions with two kind of
441 escape forms.</para>
442
443 <para>The first kind of escape form are made of a hash and a letter or a
444 number, as in: <code>#0</code>, <code>#1</code>, ..., until
445 <code>#z</code>. These codes are replaced by the corresponding input
446 values. The second kind of escape form has the format <code>@(return
447 <optional>n</optional>)</code>, it can be used as lvalue in a C expression
448 and it is used to set the n-th output value of the
449 <function>ffi:c-inline</function> form.</para>
450
451 <para>When the parameter <replaceable>one-liner</replaceable> is true, then
452 the C template must be a simple C statement that outputs a value. In this
453 case the use of <code>@(return)</code> is not allowed. When the parameter
454 <replaceable>one-liner</replaceable> is false, then the C template may be a
455 more complicated block form, with braces, conditionals, loops and spanning
456 multiple lines. In this case the output of the form can only be set using
457 <code>@(return)</code>.</para>
458
459 <para>Note that the conversion between lisp arguments and
460 <acronym>FFI</acronym> types is automatic. Note also that
461 <function>ffi:c-inline</function> cannot be used in interpreted or
462 bytecompiled code!</para>
463 </refsect1>
464
465 <refsect1>
466 <title>Examples</title>
467
468 <para>The following example implements the transcendental function
469 <function>SIN</function> using the C equivalent</para>
470 <programlisting>(ffi:c-lines "#include &lt;math.h&gt;")
471 (defun mysin (x)
472 (ffi:c-inline (x) (:double) :double "sin(#0)" :one-liner t :side-effects nil))</programlisting>
473
474 <para>This function can also be implemented using the
475 <code>@(return)</code> form as follows:</para>
476 <programlisting>(defun mysin (x)
477 (ffi:c-inline (x) (:double) :double "@(return)=sin(#0);" :side-effects nil))</programlisting>
478
479 <para>The following example is slightly more complicated as it involves
480 loops and two output values:</para>
481 <programlisting>(defun sample (x)
482 (ffi:c-inline (n1 n2) (:int :int) (values :int :int) "{
483 int n1 = #0, n2 = #1, out1 = 0, out2 = 1;
484 while (n1 &lt;= n2) {
485 out1 += n1;
486 out2 *= n1;
487 n1++;
488 }
489 @(return 0)= out1;
490 @(return 1)= out2;
491 }"
492 :side-effects nil))</programlisting>
493 </refsect1>
494 </refentry>
495 </section>
496 </chapter>
497 </book>
498 <!-- Keep this comment at the end of the file
499 Local variables:
500 mode: nxml
501 sgml-parent-document: "ecl.xml"
502 sgml-indent-step: 1
503 nxml-child-indent: 1
504 nxml-outline-child-indent: 1
505 fill-column: 79
506 End:
507 -->