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