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