0.7.5.11:
[sbcl.git] / doc / ffi.sgml
1 <chapter id="ffi"><title>The Foreign Function Interface</>
2
3 <para>This chapter describes &SBCL;'s interface to C programs and
4 libraries (and, since C interfaces are a sort of <foreignphrase>lingua
5 franca</> of the Unix world, to other programs and libraries in
6 general.)</para>
7
8 <note><para>In the modern Lisp world, the usual term for this
9 functionality is Foreign Function Interface, or <acronym>FFI</>, where
10 despite the mention of <quote>function</> in this term, <acronym>FFI</> also
11 refers to direct manipulation of C data structures as well as
12 functions. The traditional &CMUCL; terminology is Alien Interface, and
13 while that older terminology is no longer used much in the system
14 documentation, it still reflected in internal names in the
15 implementation, notably in the name of the <literal>SB-ALIEN</>
16 package.</para></note>
17
18 <sect1><title>Introduction to the Foreign Function Interface</>
19 <!-- AKA "Introduction to Aliens" in the CMU CL manual -->
20
21 <para>
22 Because of Lisp's emphasis on dynamic memory allocation and garbage
23 collection, Lisp implementations use unconventional memory representations
24 for objects.  This representation mismatch creates problems when a Lisp
25 program must share objects with programs written in another language.  There
26 are three different approaches to establishing communication:
27 <itemizedlist>
28   <listitem><para>The burden can be placed on the foreign program
29     (and programmer) by requiring the knowledge and use of the
30     representations used internally by the Lisp implementation.
31     This can require a considerable amount of <quote>glue</> code on the 
32     C side, and that code tends to be sensitively dependent on the
33     internal implementation details of the Lisp system.</para></listitem>
34   <listitem><para>The Lisp system can automatically convert objects
35     back and forth between the Lisp and foreign representations.
36     This is convenient, but translation becomes prohibitively slow
37     when large or complex data structures must be shared. This approach
38     is supported by the &SBCL; <acronym>FFI</>, and used automatically
39     by the when passing integers and strings.</para></listitem>
40   <listitem><para>The Lisp program can directly manipulate foreign
41     objects through the use of extensions to the Lisp language.
42     </para></listitem>
43 </itemizedlist>
44
45 <para>&SBCL;, like &CMUCL; before it,
46 relies primarily on the automatic conversion and direct manipulation
47 approaches. Aliens of simple scalar types are automatically converted,
48 complex types are directly manipulated in their foreign
49 representation. Furthermore, Lisp strings are represented internally 
50 with null termination bytes so that they can be passed directly to
51 C interfaces without allocating new zero-terminated copies.</para>
52
53 <para>Any foreign objects that can't automatically be converted into
54 Lisp values are represented by objects of type <type>alien-value</>.
55 Since Lisp is a dynamically typed language, even foreign objects must
56 have a run-time type; this type information is provided by
57 encapsulating the raw pointer to the foreign data within an
58 <type>alien-value</> object.</para>
59
60 <para>The type language and operations on foreign types are
61 intentionally similar to those of the C language. And as discussed
62 above, they are applicable not only to communication with native C
63 programs, but also to programs in other languages which provide
64 C-level interfaces. </para>
65
66 </sect1>
67
68 <sect1><title>Foreign Types</>
69 <!-- AKA "Alien Types" in the CMU CL manual -->
70
71 <para>Alien types have a description language based on nested list
72 structure. For example the C type
73 <programlisting>
74 struct foo {
75     int a;
76     struct foo *b[100];
77 };</programlisting>
78 has the corresponding &SBCL; FFI type
79 <programlisting>
80 (struct foo
81   (a int)
82   (b (array (* (struct foo)) 100)))</programlisting>
83 </para>
84
85 <sect2><title>Defining Foreign Types</>
86
87 <para>
88 Types may be either named or anonymous.  With structure and union
89 types, the name is part of the type specifier, allowing recursively
90 defined types such as:
91 <programlisting>(struct foo (a (* (struct foo))))</programlisting>
92 An anonymous structure or union type is specified by using the name
93 <literal>nil</>.  The <function>with-alien</> macro defines a local
94 scope which <quote>captures</> any named type definitions.  Other types
95 are not inherently named, but can be given named abbreviations using
96 the <function>define-alien-type</> macro.
97 </para>
98
99 </sect2>
100
101 <sect2><title>Foreign Types and Lisp Types</>
102
103 <para>
104 The foreign types form a subsystem of the &SBCL; type system.  An
105 <type>alien</> type specifier provides a way to use any foreign type as a
106 Lisp type specifier.  For example
107 <programlisting>(typep foo '(alien (* int)))</programlisting>
108 can be used to determine whether <varname>foo</> is a pointer to a foreign
109 <type>int</>. <type>alien</> type specifiers can be used in the same ways
110 as ordinary Lisp type specifiers (like <type>string</>.) Alien type
111 declarations are subject to the same
112 precise type checking <!-- FIXME: should be linked to id="precisetypechecking" -->
113 as any other declaration.
114 </para>
115
116 <para>
117 Note that the type identifiers used in the
118 foreign type system overlap with native Lisp type
119 specifiers in some cases.  For example, the type specifier
120 <type>(alien single-float)</type> is identical to <type>single-float</>, since
121 foreign floats are automatically converted to Lisp floats.  When
122 <function>type-of</> is called on an alien value that is not automatically
123 converted to a Lisp value, then it will return an <type>alien</> type
124 specifier.
125 </para>
126
127 </sect2>
128
129 <sect2><title>Foreign Type Specifiers</>
130
131 <note><para>
132 All foreign type names are exported from the <literal>sb-alien</>
133 package. Some foreign type names are also symbols in
134 the <literal>common-lisp</> package, in which case they are
135 reexported from the <literal>sb-alien</> package, so that
136 e.g. it is legal to refer to <type>sb-alien:single-float</>.
137 </para></note>
138
139 <para>
140 These are the basic foreign type specifiers: 
141 <!-- FIXME: There must be some better way of formatting definitions
142      in DocBook than this. I haven't found it yet, but suggestions 
143      or patches would be welcome. -->
144 <itemizedlist>
145   <listitem>
146     <para>
147       The foreign type specifier <type>(* foo)</> describes a
148       pointer to an object of type <type>foo</>.  A pointed-to type
149       <type>foo</> of <type>t</> indicates a pointer to anything,
150       similar to <type>void *</> in ANSI C. A null alien pointer can
151       be detected with the <function>sb-alien:null-alien</>
152       function.
153     </para>
154   </listitem>
155   <listitem>
156     <para> 
157       The foreign type specifier <type>(array foo &amp;optional dimensions)</>
158       describes array of the specified <literal>dimensions</>, holding
159       elements of type <type>foo</>. Note that (unlike in C) <type>(* foo)</>
160       <type>(array foo)}</> are considered to be different types when
161       type checking is done. If equivalence of pointer and array types
162       is desired, it may be explicitly coerced using
163       <function>sb-alien:cast</>.
164     </para>
165     <para>
166       Arrays are accessed using <function>sb-alien:deref</>, passing
167       the indices as additional arguments.  Elements are stored in
168       column-major order (as in C), so the first dimension determines
169       only the size of the memory block, and not the layout of the
170       higher dimensions.  An array whose first dimension is variable
171       may be specified by using <literal>nil</> as the first dimension.
172       Fixed-size arrays can be allocated as array elements, structure
173       slots or <function>sb-alien:with-alien</> variables. Dynamic
174       arrays can only be allocated using <function>sb-alien:make-alien</>.
175     </para>
176   </listitem>
177   <listitem>
178     <para>
179       The foreign type specifier
180       <type>(sb-alien:struct name &amp;rest fields)</>
181       describes a structure type with the specified <varname>name</> and
182       <varname>fields</>. Fields are allocated at the same offsets
183       used by the implementation's C compiler. If <varname>name</>
184       is <literal>nil</> then the structure is anonymous.
185     </para>  
186     <para>
187       If a named foreign <type>struct</> specifier is passed to
188       <function>define-alien-type</> or <function>with-alien</>,
189       then this defines, respectively, a new global or local foreign
190       structure type.  If no <varname>fields</> are specified, then
191       the fields are taken from the current (local or global) alien
192       structure type definition of <varname>name</>.
193     </para>
194   </listitem>
195   <listitem>
196     <para>
197       The foreign type specifier
198       <type>(sb-alien:union name &amp;rest fields)</>
199       is similar to <type>sb-alien:struct</>, but describes a union type.
200       All fields are allocated at the same offset, and the size of the
201       union is the size of the largest field.  The programmer must
202       determine which field is active from context.
203     </para>
204   </listitem>
205   <listitem>
206     <para>
207       The foreign type specifier <type>(sb-alien:enum name &amp;rest specs)</>
208       describes an enumeration type that maps between integer values
209       and keywords. If <varname>name</> is <literal>nil</>, then the
210       type is anonymous.  Each element of the <varname>specs</>
211       list is either a Lisp keyword, or a list <literal>(keyword value)</>.
212       <varname>value</> is an integer. If <varname>value</> is not
213       supplied, then it defaults to one greater than the value for
214       the preceding spec (or to zero if it is the first spec.)
215     <para>
216   </listitem>
217   <listitem>
218     <para>
219       The foreign type specifier <type>(sb-alien:signed &amp;optional bits)</>
220       specifies a signed integer with the specified number of
221       <varname>bits</> precision. The upper limit on integer
222       precision is determined by the machine's word
223       size. If <varname>bits</> is not specified, the maximum
224       size will be used.
225     </para>
226   </listitem>
227   <listitem>
228     <para>
229       The foreign type specifier <type>(integer &amp;optional bits)</> is 
230       equivalent to the corresponding type specifier using 
231       <type>sb-alien:signed</> instead of <type>integer</>.
232     </para>
233   </listitem>
234   <listitem>
235     <para>
236       The foreign type specifier
237       <type>(sb-alien:unsigned &amp;optional bits)</>
238       is like corresponding type specifier using <type>sb-alien:signed</>
239       except that the variable is treated as an unsigned integer.
240     </para>
241   </listitem>
242   <listitem>
243     <para>
244       The foreign type specifier <type>(boolean &amp;optional bits)</> is
245       similar to an enumeration type, but maps from Lisp <literal>nil</>
246       and <literal>t</> to C <literal>0</> and <literal>1</>
247       respectively. <varname>bits</> determines the amount of
248       storage allocated to hold the truth value.
249     </para>
250   </listitem>
251   <listitem>
252     <para>
253       The foreign type specifier <type>single-float</> describes a 
254       floating-point number in IEEE single-precision format.
255     </para>
256   </listitem>
257   <listitem>
258     <para>
259       The foreign type specifier <type>double-float</> describes a 
260       floating-point number in IEEE double-precision format.
261     </para>
262   </listitem>
263   <listitem>
264     <para>
265       The foreign type specifier
266       <type>(function result-type &amp;rest arg-types)</>
267       describes a foreign function that takes arguments of the specified
268       <varname>arg-types</> and returns a result of type <type>result-type</>.
269       Note that the only context where a foreign <type>function</> type
270       is directly specified is in the argument to
271       <function>sb-alien:alien-funcall</>.
272       In all other contexts, foreign functions are represented by
273       foreign function pointer types: <type>(* (function ...))</>.
274     </para>
275   </listitem>
276   <listitem>
277     <para>
278       The foreign type specifier <type>sb-alien:system-area-pointer</>
279       describes a pointer which is represented in Lisp as a
280       <type>system-area-pointer</> object. &SBCL; exports this type from
281       <literal>sb-alien</> because &CMUCL; did, but tentatively (as of
282       the first draft of this section of the manual, 2002-07-04) it is
283       deprecated, since it doesn't seem to be required by user code.
284     </para>
285   </listitem>
286   <listitem>
287     <para>
288       The foreign type specifier <type>sb-alien:void</> is 
289       used in function types to declare that no useful value
290       is returned.  Using <function>alien-funcall</>
291       to call a <type>void</> foreign function will return
292       zero values.
293     </para>
294   </listitem>
295   <listitem>
296     <para>
297       The foreign type specifier <type>sb-alien:c-string</>
298       is similar to <type>(* char)</>, but is interpreted as a
299       null-terminated string, and is automatically converted into a
300       Lisp string when accessed; or if the pointer is C <literal>NULL</>
301       or <literal>0</>, then accessing it gives Lisp <literal>nil</>.
302     </para>  
303     <para>
304       Assigning a Lisp string to a <type>c-string</> structure field or
305       variable stores the contents of the string to the memory already
306       pointed to by that variable.  When a foreign object of type
307       <type>(* char)</> is assigned to a <type>c-string</>, then the
308       <type>c-string</> pointer is assigned to.  This allows
309       <type>c-string</> pointers to be initialized.  For example:
310       <programlisting>(cl:in-package "CL-USER") ; which USEs package "SB-ALIEN"
311         (define-alien-type nil (struct foo (str c-string)))
312         (defun make-foo (str) (let ((my-foo (make-alien (struct foo))))
313         (setf (slot my-foo 'str) (make-alien char (length str))
314               (slot my-foo 'str) str) my-foo))</programlisting>
315       Storing Lisp <literal>NIL</> in a <type>c-string</> writes C
316       <literal>NULL</> to the variable.
317     </para>
318   </listitem>
319   <listitem>
320     <para>
321       <literal>sb-alien</> also exports translations of these C type
322       specifiers as foreign type specifiers:
323         <type>sb-alien:char</>,
324         <type>sb-alien:short</>,
325         <type>sb-alien:int</>,
326         <type>sb-alien:long</>,
327         <type>sb-alien:unsigned-char</>,
328         <type>sb-alien:unsigned-short</>,
329         <type>sb-alien:unsigned-int</>,
330         <type>sb-alien:unsigned-long</>,
331         <type>sb-alien:float</>, and
332         <type>sb-alien:double</>.
333     </para>
334   </listitem>
335
336 </itemizedlist>
337
338 </sect1>
339
340 <sect1><title>Operations On Foreign Values</>
341 <!-- AKA "Alien Operations" in the CMU CL manual -->
342
343 <para>This section describes how to read foreign values as Lisp
344 values, how to coerce foreign values to different kinds of foreign values, and
345 how to dynamically allocate and free foreign variables.</para>
346
347 <sect2><title>Accessing Foreign Values</>
348
349 <synopsis>(sb-alien:deref pointer-or-array &amp;rest indices)</>
350
351 <para>The <function>sb-alien:deref</> function returns the value pointed to by
352 a foreign pointer, or the value of a foreign array element. When
353 dereferencing a pointer, an optional single index can be specified to
354 give the equivalent of C pointer arithmetic; this index is scaled by
355 the size of the type pointed to. When dereferencing an array, the
356 number of indices must be the same as the number of dimensions in the
357 array type. <function>deref</> can be set with <function>setf</> to
358 assign a new value.</para>
359
360 <synopsis>(sb-alien:slot struct-or-union &amp;rest slot-names)</>
361   
362 <para>The <function>sb-alien:slot</> function extracts the value of
363 the slot named <varname>slot-name</> from a foreign <type>struct</> or
364 <type>union</>. If <varname>struct-or-union</> is a pointer to a
365 structure or union, then it is automatically dereferenced.
366 <function>sb-alien:slot</> can be set with <function>setf</> to assign
367 a new value. Note that <varname>slot-name</> is evaluated, and need
368 not be a compile-time constant (but only constant slot accesses are
369 efficiently compiled.)</para>
370
371 </sect2>
372
373 <sect2><title>Coercing Foreign Values</>
374
375 <synopsis>(sb-alien:addr alien-expr)</>
376   
377 <para>
378 The <function>sb-alien:addr</> macro
379 returns a pointer to the location specified by
380 <varname>alien-expr</>, which must be either a foreign variable, a use of
381 <function>sb-alien:deref</>, a use of <function>sb-alien:slot</>, or a use of
382 <function>sb-alien:extern-alien</>.
383 </para>
384
385 <synopsis>(sb-alien:cast foreign-value new-type)</>
386   
387 <para>The <function>sb-alien:cast</>
388 converts <varname>foreign-value</> to a new foreign value with the specified
389 <varname>new-type</>. Both types, old and new, must be foreign pointer,
390 array or function types.  Note that the resulting Lisp 
391 foreign variable object 
392 is not <function>eq</> to the
393 argument, but it does refer to the same foreign data bits.</para>
394
395 <synopsis>(sb-alien:sap-alien sap type)</>
396   
397 <para>The <function>sb-alien:sap-alien</> function converts <varname>sap</>
398 (a system area pointer) to a foreign value with the specified
399 <varname>type</>. <varname>type</> is not evaluated.
400 As of 2002-07-04, it looks as though this and other SAP functionality
401 may become deprecated, since it shouldn't be needed by user code.
402 </para>
403
404 <para>The <varname>type</> must be some foreign pointer, array, or
405 record type.</para>
406
407 <synopsis>(sb-alien:alien-sap foreign-value type)</>
408
409 <para>The <function>sb-alien:alien-sap</> function
410 returns the SAP which points to <varname>alien-value</>'s data.
411 As of 2002-07-04, it looks as though this and other SAP functionality
412 may become deprecated, since it shouldn't be needed by user code.
413 </para>
414
415 <para>The <varname>foreign-value</> must be of some foreign pointer,
416 array, or record type.</para>
417
418 </sect2>
419
420 <sect2><title>Foreign Dynamic Allocation</>
421
422 <para>Lisp code can call the C standard library functions
423 <function>malloc</> and <function>free</> to dynamically allocate and
424 deallocate foreign variables. The Lisp code shares the same allocator
425 with foreign C code, so it's OK for foreign code to call
426 <function>free</> on the result of Lisp
427 <function>sb-alien:make-alien</>, or for Lisp code to call
428 <function>sb-alien:free-alien</> on foreign objects allocated by C
429 code.</para>
430
431 <synopsis>(sb-alien:make-alien type size)</>
432   
433 <para>The <function>sb-alien:make-alien</> macro
434 returns a dynamically allocated foreign value of the specified
435 <varname>type</> (which is not evaluated.)  The allocated memory is not
436 initialized, and may contain arbitrary junk.  If supplied,
437 <varname>size</> is an expression to evaluate to compute the size of the
438 allocated object.  There are two major cases:
439 <itemizedlist>
440   <listitem>
441     <para>When <varname>type</> is a foreign array type, an array of
442     that type is allocated and a pointer to it is returned.  Note that you
443     must use <function>deref</> to change the result to an array before you
444     can use <function>deref</> to read or write elements:
445     <programlisting>
446       (cl:in-package "CL-USER") ; which USEs package "SB-ALIEN"
447       (defvar *foo* (make-alien (array char 10)))
448       (type-of *foo*) => (alien (* (array (signed 8) 10)))
449       (setf (deref (deref foo) 0) 10) => 10</programlisting>
450     If supplied, <varname>size</> is used as the first dimension for the
451     array.</para>
452   </listitem>
453   <listitem>    
454     <para>When <varname>type</> is any other foreign type, then an
455     object for that type is allocated, and a pointer to it is
456     returned.  So <function>(make-alien int)</> returns a <type>(* int)</>.
457     If <varname>size</> is specified, then a block of that many
458     objects is allocated, with the result pointing to the first one.</para>
459   </listitem>
460 </itemizedlist>
461 </para>
462  
463 <synopsis>(sb-alien:free-alien foreign-value)</>
464
465 <para>The <function>sb-alien:free-alien</> function
466 frees the storage for <varname>foreign-value</>, 
467 which must have been allocated with Lisp <function>make-alien</>
468 or C <function>malloc</>.</para>
469
470 <para>See also the <function>sb-alien:with-alien</> macro, which
471 allocates foreign values on the stack.</para>
472
473 </sect1>
474
475 <sect1><title>Foreign Variables</>
476 <!-- AKA "Alien Variables" in the CMU CL manual -->
477
478 <para>
479 Both local (stack allocated) and external (C global) foreign variables are
480 supported.
481 </para>
482
483 <sect2><title>Local Foreign Variables</>
484
485 <synopsis>(sb-alien:with-alien var-definitions &amp;body body)</>
486
487 <para>The <function>with-alien</>
488 macro establishes local 
489 foreign variables 
490 with the specified
491 alien types and names.
492 This form is analogous to defining a local variable in C: additional
493 storage is allocated, and the initial value is copied.
494 This form is less
495 analogous to LET-allocated Lisp variables, since the variables
496 can't be captured in closures: they live only for the dynamic extent
497 of the body, and referring to them outside is a gruesome error.
498 </para>
499
500 <para>The <varname>var-definitions</> argument is a list of 
501 variable definitions, each of the form
502 <programlisting>(name type &amp;optional initial-value)</programlisting>
503 The names of the variables are established as symbol-macros; the bindings have
504 lexical scope, and may be assigned with <function>setq</>
505 or <function>setf</>.
506 </para>  
507  
508 <para>The <function>with-alien</> macro also establishes
509 a new scope for named structures
510 and unions.  Any <varname>type</> specified for a variable may contain
511 named structure or union types with the slots specified.  Within the
512 lexical scope of the binding specifiers and body, a locally defined
513 foreign structure type <type>foo</> can be referenced by its name using
514 <type>(struct foo)</>.
515 </para>
516
517 </sect2>
518
519 <sect2><title>External Foreign Variables</>
520
521 <para>
522 External foreign names are strings, and Lisp names are symbols. When
523 an external foreign value is represented using a Lisp variable, there
524 must be a way to convert from one name syntax into the other. The
525 macros <function>extern-alien</>, <function>define-alien-variable</> and
526 <function>define-alien-routine</> use this conversion heuristic:
527 <itemizedlist>
528   <listitem><para>Alien names are converted to Lisp names by uppercasing and
529     replacing underscores with hyphens.</para></listitem>
530   <listitem><para>Conversely, Lisp names are converted to alien names by
531     lowercasing and replacing hyphens with underscores.</para></listitem>
532   <listitem><para>Both the Lisp symbol and alien string names may be
533     separately specified by using a list of the form
534     <programlisting>(alien-string lisp-symbol)</></para></listitem>
535 </itemizedlist>
536
537 <synopsis>(sb-alien:define-alien-variable name type)</>
538
539 <para>
540 The <function>define-alien-variable</> macro  
541 defines <varname>name</> as an external foreign variable of the
542 specified foreign <type>type</>.  <varname>name</> and <type>type</> are not
543 evaluated.  The Lisp name of the variable (see above) becomes a
544 global alien variable.  Global alien variables
545 are effectively ``global symbol macros''; a reference to the
546 variable fetches the contents of the external variable.  Similarly,
547 setting the variable stores new contents---the new contents must be
548 of the declared <type>type</>. Someday, they may well be implemented
549 using the &ANSI; <function>define-symbol-macro</> mechanism, but 
550 as of &SBCL; 0.7.5, they are still implemented using an older
551 more-or-less parallel mechanism inherited from &CMUCL;.
552 </para>
553   
554 <para>
555 For example, to access a C-level counter <varname>foo</>, one could
556 write
557 <programlisting>
558 (define-alien-variable "foo" int)
559 ;; Now it is possible to get the value of the C variable foo simply by
560 ;; referencing that Lisp variable:
561 (print foo)
562 (setf foo 14)
563 (incf foo)</programlisting>
564 </para>
565
566 <synopsis>(sb-alien:get-errno)</>
567
568 <para>
569 Since in modern C libraries, the <varname>errno</> "variable" is typically
570 no longer a variable, but some some bizarre artificial construct
571 which behaves superficially like a variable within a given thread,
572 it can no longer reliably be accessed through the ordinary 
573 <varname>define-alien-variable</> mechanism. Instead, &SBCL; provides
574 the operator <function>sb-alien:get-errno</> to allow Lisp code to read it.
575 </para>
576
577 <synopsis>(sb-alien:extern-alien name type)</>
578
579 <para>
580 The <function>extern-alien</> macro
581 returns an alien with the specified <type>type</> which
582 points to an externally defined value.  <varname>name</> is not evaluated,
583 and may be either a string or a symbol. <type>type</> is
584 an unevaluated alien type specifier.
585 </para>
586
587 </sect1>
588
589 <sect1><title>Foreign Data Structure Examples</>
590 <!-- AKA "Alien Data Structure Example" in the CMU CL manual -->
591
592 <para>
593 Now that we have alien types, operations and variables, we can manipulate
594 foreign data structures.  This C declaration 
595 <programlisting>
596 struct foo {
597     int a;
598     struct foo *b[100];
599 };</programlisting>
600 can be translated into the following alien type:
601 <programlisting>(define-alien-type nil
602   (struct foo
603     (a int)
604     (b (array (* (struct foo)) 100))))</programlisting>
605 </para>
606
607 <para>
608 Once the <type>foo</> alien type has been defined as above,
609 the C expression 
610 <programlisting>
611 struct foo f;
612 f.b[7].a</programlisting>
613 can be translated in this way:
614 <programlisting>
615 (with-alien ((f (struct foo)))
616   (slot (deref (slot f 'b) 7) 'a)
617   ;;
618   ;; Do something with f...
619   )</programlisting>
620 </para>
621
622 <para>
623 Or consider this example of an external C variable and some accesses:
624 <programlisting>
625 struct c_struct {
626         short x, y;
627         char a, b;
628         int z;
629         c_struct *n;
630 };
631 extern struct c_struct *my_struct;
632 my_struct->x++;
633 my_struct->a = 5;
634 my_struct = my_struct->n;</programlisting>
635 which can be manipulated in Lisp like this:
636 <programlisting>
637 (define-alien-type nil
638   (struct c-struct
639           (x short)
640           (y short)
641           (a char)
642           (b char)
643           (z int)
644           (n (* c-struct))))
645 (define-alien-variable "my_struct" (* c-struct))
646 (incf (slot my-struct 'x))
647 (setf (slot my-struct 'a) 5)
648 (setq my-struct (slot my-struct 'n))</programlisting>
649 </para>
650
651 </sect1>
652
653 <sect1><title>Loading Unix Object Files</>
654
655 <para>
656 Foreign object files can be loaded into the running Lisp process by
657 calling the functions <function>load-foreign</> or
658 <function>load-1-foreign</>.
659 </para>
660
661 <para> The <function>sb-alien:load-1-foreign</> function is the more
662 primitive of the two operations. It loads a single object file. into
663 the currently running Lisp. The external symbols defining routines and
664 variables are made available for future external references (e.g. by
665 <function>extern-alien</>). Forward references to foreign symbols
666 aren't supported: <function>load-1-foreign</> must be run before any
667 of the defined symbols are referenced.
668 </para>
669
670 <para><function>sb-alien:load-foreign</> is built in terms of
671 <function>load-1-foreign</> and some other machinery
672 like <function>sb-ext:run-program</>. 
673 It accepts a list of files and libraries, 
674 and runs the linker on the files and
675 libraries, creating an absolute Unix object file which is then 
676 processed by <function>load-1-foreign</>.</para>
677
678 <para> Note that as of &SBCL; 0.7.5, all foreign code (code loaded
679 with <function>load-1-function</> or <function>load-function</>) is
680 lost when a Lisp core is saved with
681 <function>sb-ext:save-lisp-and-die</>, and no attempt is made to
682 restore it when the core is loaded. Historically this has been an
683 annoyance both for &SBCL; users and for &CMUCL; users.
684 It's hard to solve this problem completely cleanly, but some
685 generally-reliable partial solution might be useful. Once someone in
686 either camp gets sufficiently annoyed to create it, some mechanism for
687 automatically restoring foreign code is likely to be added.</para>
688
689 </sect1>
690
691 <sect1><title>Foreign Function Calls</>
692
693 <para>
694 The foreign function call interface allows a Lisp program to call
695 functions written in other languages using the C calling convention.
696 </para>
697
698 <para>
699 Lisp sets up various interrupt handling routines and other environment
700 information when it first starts up, and expects these to be in place
701 at all times. The C functions called by Lisp should either not change
702 the environment, especially the interrupt entry points, or should make
703 sure that these entry points are restored when the C function returns
704 to Lisp. If a C function makes changes without restoring things to the
705 way they were when the C function was entered, there is no telling
706 what will happen.
707 </para>
708
709 <sect2><title>The <function>alien-funcall</> Primitive</title>
710
711 <synopsis>(sb-alien:alien-funcall alien-function &amp;rest arguments)</>
712
713 <para>
714 The <function>alien-funcall</> function is the foreign function call
715 primitive: <varname>alien-function</> is called with the supplied
716 <varname>arguments</> and its C return value is returned as a Lisp value.
717 The <varname>alien-function</> is an arbitrary
718 run-time expression; to refer to a constant function, use
719 <function>extern-alien</> or a value defined by
720 <function>define-alien-routine</>.
721 </para>
722   
723 <para>
724 The type of <function>alien-function</>
725 must be <type>(alien (function ...))</>
726 or <type>(alien (* (function ...)))</>.
727 The function type is used to
728 determine how to call the function (as though it was declared with
729 a prototype.)  The type need not be known at compile time, but only
730 known-type calls are efficiently compiled.  Limitations:
731 <itemizedlist>
732   <listitem><para>Structure type return values are not implemented.</></>
733   <listitem><para>Passing of structures by value is not implemented.</></>
734 </itemizedlist>
735
736 <para>
737 Here is an example which allocates a <type>(struct foo)</>, calls a foreign
738 function to initialize it, then returns a Lisp vector of all the
739 <type>(* (struct foo))</> objects filled in by the foreign call:
740 <programlisting>
741 ;; Allocate a foo on the stack.
742 (with-alien ((f (struct foo)))
743   ;; Call some C function to fill in foo fields.
744   (alien-funcall (extern-alien "mangle_foo" (function void (* foo)))
745                  (addr f))
746   ;; Find how many foos to use by getting the A field.
747   (let* ((num (slot f 'a))
748          (result (make-array num)))
749     ;; Get a pointer to the array so that we don't have to keep extracting it:
750     (with-alien ((a (* (array (* (struct foo)) 100)) (addr (slot f 'b))))
751       ;; Loop over the first N elements and stash them in the result vector.
752       (dotimes (i num)
753         (setf (svref result i) (deref (deref a) i)))
754       ;; Voila.
755       result)))</programlisting>
756 </para>
757
758 </sect2>
759
760 <sect2><title>The <function>define-alien-routine</> Macro</>
761
762 <synopsis>(sb-alien:define-alien-routine} name result-type &amp;rest arg-specifiers)</>
763
764 <para>
765 The <function>define-alien-routine</> macro is a convenience
766 for automatically generating Lisp
767 interfaces to simple foreign functions.  The primary feature is the
768 parameter style specification, which translates the C
769 pass-by-reference idiom into additional return values.
770 </para>
771   
772 <para>
773 <varname>name</> is usually a string external symbol, but may also be a
774 symbol Lisp name or a list of the foreign name and the Lisp name.
775 If only one name is specified, the other is automatically derived
776 as for <function>extern-alien</>.
777 <varname>result-type</> is the alien type of the return value.
778 </para>
779
780 <para>
781 Each element of the <varname>arg-specifiers</> list 
782 specifies an argument to the foreign function, and is
783 of the form
784 <programlisting>(aname atype &amp;optional style)</programlisting>
785 <varname>aname</> is the symbol name of the argument to the constructed
786 function (for documentation). <varname>atype</> is the alien type of
787 corresponding foreign argument.  The semantics of the actual call
788 are the same as for <function>alien-funcall</>. <varname>style</>
789 specifies how this argument should be handled at call and return time,
790 and should be one of the following
791 <itemizedlist>
792   <listitem><para><varname>:in</>specifies that the argument is
793     passed by value. This is the default. <varname>:in</> arguments
794     have no corresponding return value from the Lisp function.
795     </para></listitem>
796   <listitem><para><varname>:copy</> is similar to <varname>:in</>,
797     but the argument is copied
798     to a pre-allocated object and a pointer to this object is passed
799     to the foreign routine.</para></listitem>
800   <listitem><para><varname>:out</> specifies a pass-by-reference
801     output value.  The type of the argument must be a pointer to
802     a fixed-sized object (such as an integer or pointer).
803     <varname>:out</> and <varname>:in-out</> style cannot
804     be used with pointers to arrays, records or functions.  An
805     object of the correct size is allocated on the stack, and
806     its address is passed to the foreign function.  When the
807     function returns, the contents
808     of this location are returned as one of the values of the Lisp
809     function (and the location is automatically deallocated).
810     </para></listitem>
811   <listitem><para><varname>:in-out</> is a combination of
812     <varname>:copy</> and <varname>:out</>.
813     The argument is copied to a pre-allocated object and a pointer to
814     this object is passed to the foreign routine.  On return, the
815     contents of this location is returned as an additional value.
816     </para></listitem>
817 </itemizedlist>
818 </para>
819
820 <note>
821 <para>
822 Any efficiency-critical foreign interface function should be inline
823 expanded, which can be done by preceding the
824 <function>define-alien-routine</> call with:
825 <programlisting>(declaim (inline lisp-name))</programlisting>
826 In addition to avoiding the Lisp call overhead, this allows
827 pointers, word-integers and floats to be passed using non-descriptor
828 representations, avoiding consing.)
829 </para>
830 </note>
831
832 </sect2>
833
834 <sect2><title><function>define-alien-routine</> Example</title>
835
836 <para>
837 Consider the C function <function>cfoo</>
838 with the following calling convention:
839 <programlisting>
840 void
841 cfoo (str, a, i)
842     char *str;
843     char *a; /* update */
844     int *i; /* out */
845 {
846   /* body of cfoo(...) */
847 }</programlisting>
848 This can be described by the following call to
849 <function>define-alien-routine</>:
850 <programlisting>
851 (define-alien-routine "cfoo" void
852   (str c-string)
853   (a char :in-out)
854   (i int :out))</programlisting>
855 The Lisp function <function>cfoo</> will have
856 two arguments (<varname>str</> and <varname>a</>)
857 and two return values (<varname>a</> and <varname>i</>).
858
859 </sect2>
860
861 <sect2><title>Calling Lisp From C</>
862
863 <para>
864 Calling Lisp functions from C is sometimes possible, but is extremely
865 hackish and poorly supported as of &SBCL; 0.7.5.
866 See <function>funcall0</> ... <function>funcall3</> in
867 the runtime system. The
868 arguments must be valid &SBCL; object descriptors (so that 
869 e.g. fixnums must be
870 left-shifted by 2.) As of &SBCL; 0.7.5, the format
871 of object descriptors is documented only by the source code and 
872 by the old &CMUCL; "INTERNALS" documentation.</para>
873
874 <para> Note that the garbage collector moves objects, and won't be
875 able to fix up any references in C variables, so either turn GC off or
876 don't keep Lisp pointers in C data unless they are to statically
877 allocated objects. It is possible to use the
878 <function>sb-ext:purify</> function to place live data structures in
879 static space so that they won't move during GC. </para>
880
881 <!-- FIXME: This is a "changebar" section from the CMU CL manual.
882      I (WHN 2002-07-14) am not very familiar with this content, so 
883      I'm not immediately prepared to try to update it for SBCL, and
884      I'm not feeling masochistic enough to work to encourage this
885      kind of low-level hack anyway. However, I acknowledge that callbacks
886      are sometimes really really necessary, so I include the original
887      text in case someone is hard-core enough to benefit from it. If
888      anyone brings the information up to date for SBCL, it belong
889      either in the main manual or on a CLiki SBCL Internals page.
890 LaTeX \subsection{Accessing Lisp Arrays}
891 LaTeX 
892 LaTeX Due to the way \cmucl{} manages memory, the amount of memory that can
893 LaTeX be dynamically allocated by \code{malloc} or \funref{make-alien} is
894 LaTeX limited\footnote{\cmucl{} mmaps a large piece of memory for it's own
895 LaTeX   use and this memory is typically about 8 MB above the start of the C
896 LaTeX   heap.  Thus, only about 8 MB of memory can be dynamically
897 LaTeX   allocated.}.
898 LaTeX 
899 LaTeX To overcome this limitation, it is possible to access the content of
900 LaTeX Lisp arrays which are limited only by the amount of physical memory
901 LaTeX and swap space available.  However, this technique is only useful if
902 LaTeX the foreign function takes pointers to memory instead of allocating
903 LaTeX memory for itself.  In latter case, you will have to modify the
904 LaTeX foreign functions.
905 LaTeX 
906 LaTeX This technique takes advantage of the fact that \cmucl{} has
907 LaTeX specialized array types (\pxlref{specialized-array-types}) that match
908 LaTeX a typical C array.  For example, a \code{(simple-array double-float
909 LaTeX   (100))} is stored in memory in essentially the same way as the C
910 LaTeX array \code{double x[100]} would be.  The following function allows us
911 LaTeX to get the physical address of such a Lisp array:
912 LaTeX \begin{example}
913 LaTeX (defun array-data-address (array)
914 LaTeX   "Return the physical address of where the actual data of an array is
915 LaTeX stored.
916 LaTeX 
917 LaTeX ARRAY must be a specialized array type in CMU Lisp.  This means ARRAY
918 LaTeX must be an array of one of the following types:
919 LaTeX 
920 LaTeX                   double-float
921 LaTeX                   single-float
922 LaTeX                   (unsigned-byte 32)
923 LaTeX                   (unsigned-byte 16)
924 LaTeX                   (unsigned-byte  8)
925 LaTeX                   (signed-byte 32)
926 LaTeX                   (signed-byte 16)
927 LaTeX                   (signed-byte  8)
928 LaTeX "
929 LaTeX   (declare (type (or #+signed-array (array (signed-byte 8))
930 LaTeX                      #+signed-array (array (signed-byte 16))
931 LaTeX                      #+signed-array (array (signed-byte 32))
932 LaTeX                      (array (unsigned-byte 8))
933 LaTeX                      (array (unsigned-byte 16))
934 LaTeX                      (array (unsigned-byte 32))
935 LaTeX                      (array single-float)
936 LaTeX                      (array double-float))
937 LaTeX                  array)
938 LaTeX            (optimize (speed 3) (safety 0))
939 LaTeX            (ext:optimize-interface (safety 3)))
940 LaTeX   ;; with-array-data will get us to the actual data.  However, because
941 LaTeX   ;; the array could have been displaced, we need to know where the
942 LaTeX   ;; data starts.
943 LaTeX   (lisp::with-array-data ((data array)
944 LaTeX                           (start)
945 LaTeX                           (end))
946 LaTeX     (declare (ignore end))
947 LaTeX     ;; DATA is a specialized simple-array.  Memory is laid out like this:
948 LaTeX     ;;
949 LaTeX     ;;   byte offset    Value
950 LaTeX     ;;        0         type code (should be 70 for double-float vector)
951 LaTeX     ;;        4         4 * number of elements in vector
952 LaTeX     ;;        8         1st element of vector
953 LaTeX     ;;      ...         ...
954 LaTeX     ;;
955 LaTeX     (let ((addr (+ 8 (logandc1 7 (kernel:get-lisp-obj-address data))))
956 LaTeX           (type-size (let ((type (array-element-type data)))
957 LaTeX                        (cond ((or (equal type '(signed-byte 8))
958 LaTeX                                   (equal type '(unsigned-byte 8)))
959 LaTeX                               1)
960 LaTeX                              ((or (equal type '(signed-byte 16))
961 LaTeX                                   (equal type '(unsigned-byte 16)))
962 LaTeX                               2)
963 LaTeX                              ((or (equal type '(signed-byte 32))
964 LaTeX                                   (equal type '(unsigned-byte 32)))
965 LaTeX                               4)
966 LaTeX                              ((equal type 'single-float)
967 LaTeX                               4)
968 LaTeX                              ((equal type 'double-float)
969 LaTeX                               8)
970 LaTeX                              (t
971 LaTeX                               (error "Unknown specialized array element type"))))))
972 LaTeX       (declare (type (unsigned-byte 32) addr)
973 LaTeX                (optimize (speed 3) (safety 0) (ext:inhibit-warnings 3)))
974 LaTeX       (system:int-sap (the (unsigned-byte 32)
975 LaTeX                         (+ addr (* type-size start)))))))
976 LaTeX \end{example}
977 LaTeX 
978 LaTeX Assume we have the C function below that we wish to use:
979 LaTeX \begin{example}
980 LaTeX   double dotprod(double* x, double* y, int n)
981 LaTeX   \{
982 LaTeX     int k;
983 LaTeX     double sum = 0;
984 LaTeX 
985 LaTeX     for (k = 0; k < n; ++k) \{
986 LaTeX       sum += x[k] * y[k];
987 LaTeX     \}
988 LaTeX   \}
989 LaTeX \end{example}
990 LaTeX The following example generates two large arrays in Lisp, and calls the C
991 LaTeX function to do the desired computation.  This would not have been
992 LaTeX possible using \code{malloc} or \code{make-alien} since we need about
993 LaTeX 16 MB of memory to hold the two arrays.
994 LaTeX \begin{example}
995 LaTeX   (define-alien-routine "dotprod" double
996 LaTeX     (x (* double-float) :in)
997 LaTeX     (y (* double-float) :in)
998 LaTeX     (n int :in))
999 LaTeX     
1000 LaTeX   (let ((x (make-array 1000000 :element-type 'double-float))
1001 LaTeX         (y (make-array 1000000 :element-type 'double-float)))
1002 LaTeX     ;; Initialize X and Y somehow
1003 LaTeX     (let ((x-addr (system:int-sap (array-data-address x)))
1004 LaTeX           (y-addr (system:int-sap (array-data-address y))))
1005 LaTeX       (dotprod x-addr y-addr 1000000)))    
1006 LaTeX \end{example}
1007 LaTeX In this example, it may be useful to wrap the inner \code{let}
1008 LaTeX expression in an \code{unwind-protect} that first turns off garbage
1009 LaTeX collection and then turns garbage collection on afterwards.  This will
1010 LaTeX prevent garbage collection from moving \code{x} and \code{y} after we
1011 LaTeX have obtained the (now erroneous) addresses but before the call to
1012 LaTeX \code{dotprod} is made.
1013 LaTeX 
1014 -->
1015
1016 </sect1>
1017
1018 <sect1><title>Step-By-Step Example of the Foreign Function Interface</>
1019
1020 <para>
1021 This section presents a complete example of an interface to a somewhat
1022 complicated C function.  
1023 </para>
1024
1025 <para>
1026 Suppose you have the following C function which you want to be able to
1027 call from Lisp in the file <filename>test.c</>
1028 <programlisting>
1029 struct c_struct
1030 {
1031   int x;
1032   char *s;
1033 };
1034  
1035 struct c_struct *c_function (i, s, r, a)
1036     int i;
1037     char *s;
1038     struct c_struct *r;
1039     int a[10];
1040 {
1041   int j;
1042   struct c_struct *r2;
1043  
1044   printf("i = %d\n", i);
1045   printf("s = %s\n", s);
1046   printf("r->x = %d\n", r->x);
1047   printf("r->s = %s\n", r->s);
1048   for (j = 0; j < 10; j++) printf("a[%d] = %d.\n", j, a[j]);
1049   r2 = (struct c_struct *) malloc (sizeof(struct c_struct));
1050   r2->x = i + 5;
1051   r2->s = "a C string";
1052   return(r2);
1053 };</programlisting>
1054 </para>
1055
1056 <para>
1057 It is possible to call this C function from Lisp using the file
1058 <filename>test.lisp</> containing
1059 <programlisting>
1060 (cl:defpackage "TEST-C-CALL" (:use "CL" "SB-ALIEN" "SB-C-CALL"))
1061 (cl:in-package "TEST-C-CALL")
1062
1063 ;;; Define the record C-STRUCT in Lisp.
1064 (define-alien-type nil
1065     (struct c-struct
1066             (x int)
1067             (s c-string)))
1068
1069 ;;; Define the Lisp function interface to the C routine.  It returns a
1070 ;;; pointer to a record of type C-STRUCT.  It accepts four parameters:
1071 ;;; I, an int; S, a pointer to a string; R, a pointer to a C-STRUCT
1072 ;;; record; and A, a pointer to the array of 10 ints.
1073 ;;;
1074 ;;; The INLINE declaration eliminates some efficiency notes about heap
1075 ;;; allocation of alien values.
1076 (declaim (inline c-function))
1077 (define-alien-routine c-function
1078     (* (struct c-struct))
1079   (i int)
1080   (s c-string)
1081   (r (* (struct c-struct)))
1082   (a (array int 10)))
1083
1084 ;;; a function which sets up the parameters to the C function and
1085 ;;; actually calls it
1086 (defun call-cfun ()
1087   (with-alien ((ar (array int 10))
1088                (c-struct (struct c-struct)))
1089     (dotimes (i 10)                     ; Fill array.
1090       (setf (deref ar i) i))
1091     (setf (slot c-struct 'x) 20)
1092     (setf (slot c-struct 's) "a Lisp string")
1093
1094     (with-alien ((res (* (struct c-struct))
1095                       (c-function 5 "another Lisp string" (addr c-struct) ar)))
1096       (format t "~&amp;back from C function~%")
1097       (multiple-value-prog1
1098           (values (slot res 'x)
1099                   (slot res 's))
1100
1101         ;; Deallocate result. (after we are done referring to it:
1102         ;; "Pillage, *then* burn.")
1103         (free-alien res)))))</programlisting>
1104 </para>
1105
1106 <para>
1107 To execute the above example, it is necessary to compile the C routine,
1108 e.g.:
1109 <userinput>cc -c test.c</>
1110 (In order to enable incremental loading with some linkers, you may need
1111 to say
1112 <userinput>cc -G 0 -c test.c</>)
1113 </para>
1114
1115 <para>
1116 Once the C code has been compiled, you can start up Lisp and load it in:
1117 <userinput>sbcl</>.
1118 Lisp should start up with its normal prompt.</para>
1119
1120 <para>
1121 Within Lisp, 
1122 compile the Lisp file. (This step can be done separately. You don't
1123 have to recompile every time.)
1124 <userinput>(compile-file "test.lisp")</>
1125
1126 <para>
1127 Within Lisp, load the foreign object file to define the necessary
1128 symbols:
1129 <userinput>(load-foreign "test.o")</>.
1130 This must be done before loading any code that refers
1131 to these symbols.
1132 <para>
1133
1134 <para>
1135 Now you can load the compiled Lisp ("fasl") file into Lisp:
1136 <userinput>(load "test.fasl")</>
1137 And once the Lisp file is loaded, you can call the 
1138 Lisp routine that sets up the parameters and calls the C
1139 function:
1140 <userinput>(test-c-call::call-cfun)</>
1141 </para>
1142
1143 <para>
1144 The C routine should print the following information to standard output:
1145 <!-- FIXME: What should be here is a verbatim environment for computer
1146      output, but since I don't know one in DocBook, I made do with
1147      PROGRAMLISTING for now... -->
1148 <programlisting>i = 5
1149 s = another Lisp string
1150 r->x = 20
1151 r->s = a Lisp string
1152 a[0] = 0.
1153 a[1] = 1.
1154 a[2] = 2.
1155 a[3] = 3.
1156 a[4] = 4.
1157 a[5] = 5.
1158 a[6] = 6.
1159 a[7] = 7.
1160 a[8] = 8.
1161 a[9] = 9.</programlisting>
1162 After return from the C function,
1163 the Lisp wrapper function should print the following output:
1164 <programlisting>back from C function</programlisting>
1165 And upon return from the Lisp wrapper function,
1166 before the next prompt is printed, the
1167 Lisp read-eval-print loop should print the following return values:
1168 <!-- FIXME: As above, it's not a program listing, but computer output... -->
1169 <programlisting>
1170 10
1171 "a C string"
1172 </programlisting>
1173 </para>
1174
1175 </sect1>
1176
1177 </chapter>