1 @node Foreign Function Interface
2 @comment node-name, next, previous, up
3 @chapter Foreign Function Interface
5 This chapter describes SBCL's interface to C programs and
6 libraries (and, since C interfaces are a sort of @emph{lingua
7 franca} of the Unix world, to other programs and libraries in
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.
22 * Introduction to the Foreign Function Interface::
24 * Operations On Foreign Values::
26 * Foreign Data Structure Examples::
27 * Loading Shared Object Files::
28 * Foreign Function Calls::
29 * Step-By-Step Example of the Foreign Function Interface::
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
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:
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.
52 The Lisp system can automatically convert objects back and forth between
53 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 when passing integers and strings.
59 The Lisp program can directly manipulate foreign objects through the
60 use of extensions to the Lisp language.
64 SBCL, like CMUCL before it, relies primarily on the automatic
65 conversion and direct manipulation approaches. The @code{SB-ALIEN}
66 package provides a facility wherein foreign values of simple scalar
67 types are automatically converted and complex types are directly
68 manipulated in their foreign representation. Additionally the
69 lower-level System Area Pointers (or @acronym{SAP}s) can be used where
70 necessary to provide untyped access to foreign memory.
72 Any foreign objects that can't automatically be converted into Lisp
73 values are represented by objects of type @code{alien-value}. Since
74 Lisp is a dynamically typed language, even foreign objects must have a
75 run-time type; this type information is provided by encapsulating the
76 raw pointer to the foreign data within an @code{alien-value} object.
78 The type language and operations on foreign types are
79 intentionally similar to those of the C language.
82 @comment node-name, next, previous, up
83 @section Foreign Types
84 @c AKA "Alien Types" in the CMU CL manual
86 Alien types have a description language based on nested list
87 structure. For example the C type
96 has the corresponding SBCL @acronym{FFI} type
101 (b (array (* (struct foo)) 100)))
106 * Defining Foreign Types::
107 * Foreign Types and Lisp Types::
108 * Foreign Type Specifiers::
111 @node Defining Foreign Types
112 @comment node-name, next, previous, up
113 @subsection Defining Foreign Types
115 Types may be either named or anonymous. With structure and union
116 types, the name is part of the type specifier, allowing recursively
117 defined types such as:
120 (struct foo (a (* (struct foo))))
123 An anonymous structure or union type is specified by using the name
124 @code{nil}. The @code{with-alien} macro defines a local scope which
125 ``captures'' any named type definitions. Other types are not
126 inherently named, but can be given named abbreviations using the
127 @code{define-alien-type} macro.
129 @node Foreign Types and Lisp Types
130 @comment node-name, next, previous, up
131 @subsection Foreign Types and Lisp Types
133 The foreign types form a subsystem of the SBCL type system. An
134 @code{alien} type specifier provides a way to use any foreign type as a
135 Lisp type specifier. For example,
138 (typep @var{foo} '(alien (* int)))
141 can be used to determine whether @var{foo} is a pointer to a foreign
142 @code{int}. @code{alien} type specifiers can be used in the same ways
143 as ordinary Lisp type specifiers (like @code{string}.) Alien type
144 declarations are subject to the same precise type checking as any
145 other declaration. @xref{Precise Type Checking}.
147 Note that the type identifiers used in the foreign type system overlap
148 with native Lisp type specifiers in some cases. For example, the type
149 specifier @code{(alien single-float)} is identical to
150 @code{single-float}, since foreign floats are automatically converted
151 to Lisp floats. When @code{type-of} is called on an alien value that
152 is not automatically converted to a Lisp value, then it will return an
153 @code{alien} type specifier.
155 @node Foreign Type Specifiers
156 @comment node-name, next, previous, up
157 @subsection Foreign Type Specifiers
159 Note: All foreign type names are exported from the @code{sb-alien}
160 package. Some foreign type names are also symbols in
161 the @code{common-lisp} package, in which case they are
162 reexported from the @code{sb-alien} package, so that
163 e.g. it is legal to refer to @code{sb-alien:single-float}.
165 These are the basic foreign type specifiers:
169 The foreign type specifier @code{(* @var{foo})} describes a pointer to
170 an object of type @var{foo}. A pointed-to type @var{foo} of @code{t}
171 indicates a pointer to anything, similar to @code{void *} in
172 ANSI C. A null alien pointer can be detected with the
173 @code{sb-alien:null-alien} function.
176 The foreign type specifier @code{(array @var{foo} &rest
177 dimensions)} describes array of the specified @code{dimensions},
178 holding elements of type @var{foo}. Note that (unlike in C) @code{(*
179 @var{foo})} and @code{(array @var{foo})} are considered to be
180 different types when type checking is done. If equivalence of pointer
181 and array types is desired, it may be explicitly coerced using
182 @code{sb-alien:cast}.
184 Arrays are accessed using @code{sb-alien:deref}, passing the indices
185 as additional arguments. Elements are stored in column-major order
186 (as in C), so the first dimension determines only the size of the
187 memory block, and not the layout of the higher dimensions. An array
188 whose first dimension is variable may be specified by using @code{nil}
189 as the first dimension. Fixed-size arrays can be allocated as array
190 elements, structure slots or @code{sb-alien:with-alien}
191 variables. Dynamic arrays can only be allocated using
192 @code{sb-alien:make-alien}.
195 The foreign type specifier @code{(sb-alien:struct @var{name} &rest
196 @var{fields})} describes a structure type with the specified
197 @var{name} and @var{fields}. Fields are allocated at the same offsets
198 used by the implementation's C compiler, as guessed by the SBCL
199 internals. An optional @code{:alignment} keyword argument can be
200 specified for each field to explicitly control the alignment of a
201 field. If @var{name} is @code{nil} then the structure is anonymous.
203 If a named foreign @code{struct} specifier is passed to
204 @code{define-alien-type} or @code{with-alien}, then this defines,
205 respectively, a new global or local foreign structure type. If no
206 @var{fields} are specified, then the fields are taken
207 from the current (local or global) alien structure type definition of
211 The foreign type specifier @code{(sb-alien:union @var{name} &rest
212 @var{fields})} is similar to @code{sb-alien:struct}, but describes a
213 union type. All fields are allocated at the same offset, and the size
214 of the union is the size of the largest field. The programmer must
215 determine which field is active from context.
218 The foreign type specifier @code{(sb-alien:enum @var{name} &rest
219 @var{specs})} describes an enumeration type that maps between integer
220 values and symbols. If @var{name} is @code{nil}, then the type is
221 anonymous. Each element of the @var{specs} list is either a Lisp
222 symbol, or a list @code{(@var{symbol} @var{value})}. @var{value} is
223 an integer. If @var{value} is not supplied, then it defaults to one
224 greater than the value for the preceding spec (or to zero if it is the
228 The foreign type specifier @code{(sb-alien:signed &optional
229 @var{bits})} specifies a signed integer with the specified number of
230 @var{bits} precision. The upper limit on integer
231 precision is determined by the machine's word size. If
232 @var{bits} is not specified, the maximum size will be
236 The foreign type specifier @code{(integer &optional @var{bits})}
237 is equivalent to the corresponding type specifier using
238 @code{sb-alien:signed} instead of @code{integer}.
241 The foreign type specifier @code{(sb-alien:unsigned &optional
242 @var{bits})} is like corresponding type specifier using
243 @code{sb-alien:signed} except that the variable is treated as an
247 The foreign type specifier @code{(boolean &optional @var{bits})} is
248 similar to an enumeration type, but maps from Lisp @code{nil} and
249 @code{t} to C @code{0} and @code{1} respectively. @var{bits}
250 determines the amount of storage allocated to hold the truth value.
253 The foreign type specifier @code{single-float} describes a
254 floating-point number in IEEE single-precision format.
257 The foreign type specifier @code{double-float} describes a
258 floating-point number in IEEE double-precision format.
261 The foreign type specifier @code{(function @var{result-type} &rest
262 @var{arg-types})} describes a foreign function that takes arguments of
263 the specified @var{arg-types} and returns a result of type
264 @var{result-type}. Note that the only context where a foreign
265 @code{function} type is directly specified is in the argument to
266 @code{sb-alien:alien-funcall}. In all other contexts, foreign
267 functions are represented by foreign function pointer types: @code{(*
268 (function @dots{}))}.
271 The foreign type specifier @code{sb-alien:system-area-pointer}
272 describes a pointer which is represented in Lisp as a
273 @code{system-area-pointer} object. SBCL exports this type from
274 @code{sb-alien} because CMUCL did, but tentatively (as of the first
275 draft of this section of the manual, SBCL 0.7.6) it is deprecated,
276 since it doesn't seem to be required by user code.
279 The foreign type specifier @code{sb-alien:void} is used in function
280 types to declare that no useful value is returned. Using
281 @code{alien-funcall} to call a @code{void} foreign function will
285 @cindex External formats
286 The foreign type specifier @code{(sb-alien:c-string &key
287 external-format element-type not-null)} is similar to
288 @code{(* char)}, but is interpreted as a null-terminated string, and
289 is automatically converted into a Lisp string when accessed; or if the
290 pointer is C @code{NULL} or @code{0}, then accessing it gives Lisp
291 @code{nil} unless @code{not-null} is true, in which case a type-error
294 External format conversion is automatically done when Lisp strings are
295 passed to foreign code, or when foreign strings are passed to Lisp code.
296 If the type specifier has an explicit @code{external-format}, that
297 external format will be used. Otherwise a default external format that
298 has been determined at SBCL startup time based on the current locale
299 settings will be used. For example, when the following alien routine is
300 called, the Lisp string given as argument is converted to an
301 @code{ebcdic} octet representation.
304 (define-alien-routine test int (str (c-string :external-format :ebcdic-us)))
307 Lisp strings of type @code{base-string} are stored with a trailing NUL
308 termination, so no copying (either by the user or the implementation) is
309 necessary when passing them to foreign code, assuming that the
310 @code{external-format} and @code{element-type} of the @code{c-string}
311 type are compatible with the internal representation of the string. For
312 an SBCL built with Unicode support that means an @code{external-format}
313 of @code{:ascii} and an @code{element-type} of @code{base-char}. Without
314 Unicode support the @code{external-format} can also be
315 @code{:iso-8859-1}, and the @code{element-type} can also be
316 @code{character}. If the @code{external-format} or @code{element-type}
317 is not compatible, or the string is a @code{(simple-array character
318 (*))}, this data is copied by the implementation as required.
320 Assigning a Lisp string to a @code{c-string} structure field or
321 variable stores the contents of the string to the memory already
322 pointed to by that variable. When a foreign object of type @code{(*
323 char)} is assigned to a @code{c-string}, then the
324 @code{c-string} pointer is assigned to. This allows
325 @code{c-string} pointers to be initialized. For example:
328 (cl:in-package "CL-USER") ; which USEs package "SB-ALIEN"
330 (define-alien-type nil (struct foo (str c-string)))
332 (defun make-foo (str)
333 (let ((my-foo (make-alien (struct foo))))
334 (setf (slot my-foo 'str) (make-alien char (length str))
335 (slot my-foo 'str) str)
339 Storing Lisp @code{NIL} in a @code{c-string} writes C @code{NULL} to
343 @code{sb-alien} also exports translations of these C type
344 specifiers as foreign type specifiers:
349 @code{unsigned-char},
350 @code{unsigned-short},
352 @code{unsigned-long},
353 @code{float}, @code{double},
354 @code{size-t}, and @code{off-t}.
358 @node Operations On Foreign Values
359 @comment node-name, next, previous, up
360 @section Operations On Foreign Values
361 @c AKA "Alien Operations" in the CMU CL manual
363 This section describes how to read foreign values as Lisp values, how
364 to coerce foreign values to different kinds of foreign values, and how
365 to dynamically allocate and free foreign variables.
368 * Accessing Foreign Values::
369 * Coercing Foreign Values::
370 * Foreign Dynamic Allocation::
373 @node Accessing Foreign Values
374 @comment node-name, next, previous, up
375 @subsection Accessing Foreign Values
377 @defun @sbalien{deref} @var{pointer-or-array} &rest @var{indices}
379 The @code{sb-alien:deref} function returns the value pointed to by a
380 foreign pointer, or the value of a foreign array element. When
381 dereferencing a pointer, an optional single index can be specified to
382 give the equivalent of C pointer arithmetic; this index is scaled by
383 the size of the type pointed to. When dereferencing an array, the
384 number of indices must be the same as the number of dimensions in the
385 array type. @code{deref} can be set with @code{setf} to assign a new
389 @defun @sbalien{slot} @var{struct-or-union} @var{slot-name}
391 The @code{sb-alien:slot} function extracts the value of the slot named
392 @var{slot-name} from a foreign @code{struct} or @code{union}. If
393 @var{struct-or-union} is a pointer to a structure or union, then it is
394 automatically dereferenced. @code{sb-alien:slot} can be set with
395 @code{setf} to assign a new value. Note that @var{slot-name} is
396 evaluated, and need not be a compile-time constant (but only constant
397 slot accesses are efficiently compiled).
401 @subsubsection Untyped memory
403 As noted at the beginning of the chapter, the System Area Pointer
404 facilities allow untyped access to foreign memory. @acronym{SAP}s can
405 be converted to and from the usual typed foreign values using
406 @code{sap-alien} and @code{alien-sap} (described elsewhere), and also
407 to and from integers - raw machine addresses. They should thus be
408 used with caution; corrupting the Lisp heap or other memory with
409 @acronym{SAP}s is trivial.
411 @defun @sbsys{int-sap} @var{machine-address}
413 Creates a @acronym{SAP} pointing at the virtual address
414 @var{machine-address}.
417 @defun @sbsys{sap-ref-32} @var{sap} @var{offset}
419 Access the value of the memory location at @var{offset} bytes from
420 @var{sap}. This form may also be used with @code{setf} to alter the
421 memory at that location.
424 @defun @sbsys{sap=} @var{sap1} @var{sap2}
426 Compare @var{sap1} and @var{sap2} for equality.
429 Similarly named functions exist for accessing other sizes of word,
430 other comparisons, and other conversions. The reader is invited to
431 use @code{apropos} and @code{describe} for more details
434 (apropos "sap" :sb-sys)
438 @node Coercing Foreign Values
439 @comment node-name, next, previous, up
440 @subsection Coercing Foreign Values
442 @defmac @sbalien{addr} @var{alien-expr}
444 The @code{sb-alien:addr} macro returns a pointer to the location
445 specified by @var{alien-expr}, which must be either a foreign
446 variable, a use of @code{sb-alien:deref}, a use of
447 @code{sb-alien:slot}, or a use of @code{sb-alien:extern-alien}.
450 @defmac @sbalien{cast} @var{foreign-value} @var{new-type}
452 The @code{sb-alien:cast} macro converts @var{foreign-value} to a new
453 foreign value with the specified @var{new-type}. Both types, old and
454 new, must be foreign pointer, array or function types. Note that the
455 resulting Lisp foreign variable object is not @code{eq} to the
456 argument, but it does refer to the same foreign data bits.
459 @defmac @sbalien{sap-alien} @var{sap} @var{type}
461 The @code{sb-alien:sap-alien} macro converts @var{sap} (a system
462 area pointer) to a foreign value with the specified
463 @var{type}. @var{type} is not evaluated.
465 The @var{type} must be some foreign pointer, array, or record type.
468 @defun @sbalien{alien-sap} @var{foreign-value}
470 The @code{sb-alien:alien-sap} function returns the @acronym{SAP} which
471 points to @var{alien-value}'s data.
473 The @var{foreign-value} must be of some foreign pointer, array, or
478 @node Foreign Dynamic Allocation
479 @comment node-name, next, previous, up
480 @subsection Foreign Dynamic Allocation
482 Lisp code can call the C standard library functions @code{malloc} and
483 @code{free} to dynamically allocate and deallocate foreign variables.
484 The Lisp code shares the same allocator with foreign C code, so it's
485 OK for foreign code to call @code{free} on the result of Lisp
486 @code{sb-alien:make-alien}, or for Lisp code to call
487 @code{sb-alien:free-alien} on foreign objects allocated by C code.
489 @include macro-sb-alien-make-alien.texinfo
490 @include fun-sb-alien-make-alien-string.texinfo
491 @include fun-sb-alien-free-alien.texinfo
493 @node Foreign Variables
494 @comment node-name, next, previous, up
495 @section Foreign Variables
496 @c AKA "Alien Variables" in the CMU CL manual
498 Both local (stack allocated) and external (C global) foreign variables
502 * Local Foreign Variables::
503 * External Foreign Variables::
506 @node Local Foreign Variables
507 @comment node-name, next, previous, up
508 @subsection Local Foreign Variables
510 @defmac @sbalien{with-alien} @var{var-definitions} &body @var{body}
512 The @code{with-alien} macro establishes local foreign variables with
513 the specified alien types and names. This form is analogous to
514 defining a local variable in C: additional storage is allocated, and
515 the initial value is copied. This form is less analogous to
516 @code{LET}-allocated Lisp variables, since the variables can't be
517 captured in closures: they live only for the dynamic extent of the
518 body, and referring to them outside is a gruesome error.
520 The @var{var-definitions} argument is a list of
521 variable definitions, each of the form
523 (@var{name} @var{type} &optional @var{initial-value})
526 The names of the variables are established as symbol-macros; the
527 bindings have lexical scope, and may be assigned with @code{setq} or
530 The @code{with-alien} macro also establishes a new scope for named
531 structures and unions. Any @var{type} specified for a variable may
532 contain named structure or union types with the slots specified.
533 Within the lexical scope of the binding specifiers and body, a locally
534 defined foreign structure type @var{foo} can be referenced by its name
535 using @code{(struct @var{foo})}.
538 @node External Foreign Variables
539 @comment node-name, next, previous, up
540 @subsection External Foreign Variables
542 External foreign names are strings, and Lisp names are symbols. When
543 an external foreign value is represented using a Lisp variable, there
544 must be a way to convert from one name syntax into the other. The
545 macros @code{extern-alien}, @code{define-alien-variable} and
546 @code{define-alien-routine} use this conversion heuristic:
551 Alien names are converted to Lisp names by uppercasing and replacing
552 underscores with hyphens.
555 Conversely, Lisp names are converted to alien names by lowercasing and
556 replacing hyphens with underscores.
559 Both the Lisp symbol and alien string names may be separately
560 specified by using a list of the form
563 (alien-string lisp-symbol)
568 @defmac @sbalien{define-alien-variable} @var{name} @var{type}
570 The @code{define-alien-variable} macro defines @var{name} as an
571 external foreign variable of the specified foreign @code{type}.
572 @var{name} and @code{type} are not evaluated. The Lisp name of the
573 variable (see above) becomes a global alien variable. Global alien
574 variables are effectively ``global symbol macros''; a reference to the
575 variable fetches the contents of the external variable. Similarly,
576 setting the variable stores new contents -- the new contents must be
577 of the declared @code{type}. Someday, they may well be implemented
578 using the @acronym{ANSI} @code{define-symbol-macro} mechanism, but as
579 of SBCL 0.7.5, they are still implemented using an older more-or-less
580 parallel mechanism inherited from CMUCL.
582 For example, to access a C-level counter @var{foo}, one could write
585 (define-alien-variable "foo" int)
586 ;; Now it is possible to get the value of the C variable foo simply by
587 ;; referencing that Lisp variable:
594 @defun @sbalien{get-errno}
596 Since in modern C libraries, the @code{errno} ``variable'' is typically
597 no longer a variable, but some bizarre artificial construct
598 which behaves superficially like a variable within a given thread,
599 it can no longer reliably be accessed through the ordinary
600 @code{define-alien-variable} mechanism. Instead, SBCL provides
601 the operator @code{sb-alien:get-errno} to allow Lisp code to read it.
604 @defmac @sbalien{extern-alien} @var{name} @var{type}
606 The @code{extern-alien} macro returns an alien with the specified
607 @var{type} which points to an externally defined value. @var{name} is
608 not evaluated, and may be either a string or a symbol. @var{type} is
609 an unevaluated alien type specifier.
612 @node Foreign Data Structure Examples
613 @comment node-name, next, previous, up
614 @section Foreign Data Structure Examples
615 @c AKA "Alien Data Structure Example" in the CMU CL manual
617 Now that we have alien types, operations and variables, we can
618 manipulate foreign data structures. This C declaration
627 can be translated into the following alien type:
630 (define-alien-type nil
633 (b (array (* (struct foo)) 100))))
636 Once the @code{foo} alien type has been defined as above, the C
644 can be translated in this way:
647 (with-alien ((f (struct foo)))
648 (slot (deref (slot f 'b) 7) 'a)
650 ;; Do something with f...
654 Or consider this example of an external C variable and some accesses:
663 extern struct c_struct *my_struct;
666 my_struct = my_struct->n;
669 which can be manipulated in Lisp like this:
672 (define-alien-type nil
680 (define-alien-variable "my_struct" (* c-struct))
681 (incf (slot my-struct 'x))
682 (setf (slot my-struct 'a) 5)
683 (setq my-struct (slot my-struct 'n))
686 @node Loading Shared Object Files
687 @comment node-name, next, previous, up
688 @section Loading Shared Object Files
690 Foreign object files can be loaded into the running Lisp process by
691 calling @code{load-shared-object}.
693 @include fun-sb-alien-load-shared-object.texinfo
695 @include fun-sb-alien-unload-shared-object.texinfo
697 @node Foreign Function Calls
698 @comment node-name, next, previous, up
699 @section Foreign Function Calls
701 The foreign function call interface allows a Lisp program to call
702 many functions written in languages that use the C calling convention.
704 Lisp sets up various signal handling routines and other environment
705 information when it first starts up, and expects these to be in place
706 at all times. The C functions called by Lisp should not change the
707 environment, especially the signal handlers: the signal handlers
708 installed by Lisp typically have interesting flags set (e.g to request
709 machine context information, or for signal delivery on an alternate
710 stack) which the Lisp runtime relies on for correct operation.
711 Precise details of how this works may change without notice between
712 versions; the source, or the brain of a friendly SBCL developer, is
713 the only documentation. Users of a Lisp built with the
714 @code{:sb-thread} feature should also read the section about threads,
718 * The alien-funcall Primitive::
719 * The define-alien-routine Macro::
720 * define-alien-routine Example::
721 * Calling Lisp From C::
724 @node The alien-funcall Primitive
725 @comment node-name, next, previous, up
726 @subsection The @code{alien-funcall} Primitive
728 @defun @sbalien{alien-funcall} @var{alien-function} &rest @var{arguments}
730 The @code{alien-funcall} function is the foreign function call
731 primitive: @var{alien-function} is called with the supplied
732 @var{arguments} and its C return value is returned as a Lisp value.
733 The @var{alien-function} is an arbitrary run-time expression; to refer
734 to a constant function, use @code{extern-alien} or a value defined by
735 @code{define-alien-routine}.
737 The type of @code{alien-function} must be @code{(alien (function
738 ...))} or @code{(alien (* (function ...)))}. The function type is
739 used to determine how to call the function (as though it was declared
740 with a prototype.) The type need not be known at compile time, but
741 only known-type calls are efficiently compiled. Limitations:
746 Structure type return values are not implemented.
749 Passing of structures by value is not implemented.
755 Here is an example which allocates a @code{(struct foo)}, calls a
756 foreign function to initialize it, then returns a Lisp vector of all
757 the @code{(* (struct foo))} objects filled in by the foreign call:
760 ;; Allocate a foo on the stack.
761 (with-alien ((f (struct foo)))
762 ;; Call some C function to fill in foo fields.
763 (alien-funcall (extern-alien "mangle_foo" (function void (* foo)))
765 ;; Find how many foos to use by getting the A field.
766 (let* ((num (slot f 'a))
767 (result (make-array num)))
768 ;; Get a pointer to the array so that we don't have to keep extracting it:
769 (with-alien ((a (* (array (* (struct foo)) 100)) (addr (slot f 'b))))
770 ;; Loop over the first N elements and stash them in the result vector.
772 (setf (svref result i) (deref (deref a) i)))
777 @node The define-alien-routine Macro
778 @comment node-name, next, previous, up
779 @subsection The @code{define-alien-routine} Macro
781 @defmac @sbalien{define-alien-routine} @var{name} @var{result-type} &rest @var{arg-specifiers}
783 The @code{define-alien-routine} macro is a convenience for
784 automatically generating Lisp interfaces to simple foreign functions.
785 The primary feature is the parameter style specification, which
786 translates the C pass-by-reference idiom into additional return
789 @var{name} is usually a string external symbol, but may also be a
790 symbol Lisp name or a list of the foreign name and the Lisp name. If
791 only one name is specified, the other is automatically derived as for
792 @code{extern-alien}. @var{result-type} is the alien type of the
795 Each element of the @var{arg-specifiers} list
796 specifies an argument to the foreign function, and is
799 (aname atype &optional style)
802 @var{aname} is the symbol name of the argument to the constructed
803 function (for documentation). @var{atype} is the alien type of
804 corresponding foreign argument. The semantics of the actual call are
805 the same as for @code{alien-funcall}. @var{style} specifies how this
806 argument should be handled at call and return time, and should be one
812 @code{:in} specifies that the argument is passed by value. This is the
813 default. @code{:in} arguments have no corresponding return value from
817 @code{:copy} is similar to @code{:in}, but the argument is copied to a
818 pre-allocated object and a pointer to this object is passed to the
822 @code{:out} specifies a pass-by-reference output value. The type of
823 the argument must be a pointer to a fixed-sized object (such as an
824 integer or pointer). @code{:out} and @code{:in-out} style cannot be
825 used with pointers to arrays, records or functions. An object of the
826 correct size is allocated on the stack, and its address is passed to
827 the foreign function. When the function returns, the contents of this
828 location are returned as one of the values of the Lisp function (and
829 the location is automatically deallocated).
832 @code{:in-out} is a combination of @code{:copy} and @code{:out}. The
833 argument is copied to a pre-allocated object and a pointer to this
834 object is passed to the foreign routine. On return, the contents of
835 this location is returned as an additional value.
840 Note: Any efficiency-critical foreign interface function should be inline
841 expanded, which can be done by preceding the
842 @code{define-alien-routine} call with:
845 (declaim (inline lisp-name))
848 In addition to avoiding the Lisp call overhead, this allows
849 pointers, word-integers and floats to be passed using non-descriptor
850 representations, avoiding consing.)
855 @node define-alien-routine Example
856 @comment node-name, next, previous, up
857 @subsection @code{define-alien-routine} Example
859 Consider the C function @code{cfoo} with the following calling
866 char *a; /* update */
869 /* body of cfoo(...) */
873 This can be described by the following call to
874 @code{define-alien-routine}:
877 (define-alien-routine "cfoo" void
883 The Lisp function @code{cfoo} will have two arguments (@var{str} and
884 @var{a}) and two return values (@var{a} and @var{i}).
886 @node Calling Lisp From C
887 @comment node-name, next, previous, up
888 @subsection Calling Lisp From C
890 Calling Lisp functions from C is sometimes possible, but is extremely
891 hackish and poorly supported as of SBCL 0.7.5. See @code{funcall0}
892 @dots{} @code{funcall3} in the runtime system. The arguments must be
893 valid SBCL object descriptors (so that e.g. fixnums must be
894 left-shifted by 2.) As of SBCL 0.7.5, the format of object descriptors
895 is documented only by the source code and, in parts, by the old CMUCL
896 @file{INTERNALS} documentation.
898 Note that the garbage collector moves objects, and won't be
899 able to fix up any references in C variables. There are three
900 mechanisms for coping with this:
904 The @code{sb-ext:purify} moves all live Lisp
905 data into static or read-only areas such that it will never be moved
906 (or freed) again in the life of the Lisp session
909 @code{sb-sys:with-pinned-objects} is a macro which arranges for some
910 set of objects to be pinned in memory for the dynamic extent of its
911 body forms. On ports which use the generational garbage collector (as
912 of SBCL 0.8.3, only the x86) this has a page granularity - i.e. the
913 entire 4k page or pages containing the objects will be locked down. On
914 other ports it is implemented by turning off GC for the duration (so
915 could be said to have a whole-world granularity).
918 Disable GC, using the @code{without-gcing} macro.
921 @c <!-- FIXME: This is a "changebar" section from the CMU CL manual.
922 @c I (WHN 2002-07-14) am not very familiar with this content, so
923 @c I'm not immediately prepared to try to update it for SBCL, and
924 @c I'm not feeling masochistic enough to work to encourage this
925 @c kind of low-level hack anyway. However, I acknowledge that callbacks
926 @c are sometimes really really necessary, so I include the original
927 @c text in case someone is hard-core enough to benefit from it. If
928 @c anyone brings the information up to date for SBCL, it belong
929 @c either in the main manual or on a CLiki SBCL Internals page.
930 @c LaTeX \subsection{Accessing Lisp Arrays}
932 @c LaTeX Due to the way \cmucl{} manages memory, the amount of memory that can
933 @c LaTeX be dynamically allocated by \code{malloc} or \funref{make-alien} is
934 @c LaTeX limited\footnote{\cmucl{} mmaps a large piece of memory for it's own
935 @c LaTeX use and this memory is typically about 8 MB above the start of the C
936 @c LaTeX heap. Thus, only about 8 MB of memory can be dynamically
937 @c LaTeX allocated.}.
939 @c Empirically determined to be considerably >8Mb on this x86 linux
940 @c machine, but I don't know what the actual values are - dan 2003.09.01
942 @c Note that this technique is used in SB-GROVEL in the SBCL contrib
945 @c LaTeX To overcome this limitation, it is possible to access the content of
946 @c LaTeX Lisp arrays which are limited only by the amount of physical memory
947 @c LaTeX and swap space available. However, this technique is only useful if
948 @c LaTeX the foreign function takes pointers to memory instead of allocating
949 @c LaTeX memory for itself. In latter case, you will have to modify the
950 @c LaTeX foreign functions.
952 @c LaTeX This technique takes advantage of the fact that \cmucl{} has
953 @c LaTeX specialized array types (\pxlref{specialized-array-types}) that match
954 @c LaTeX a typical C array. For example, a \code{(simple-array double-float
955 @c LaTeX (100))} is stored in memory in essentially the same way as the C
956 @c LaTeX array \code{double x[100]} would be. The following function allows us
957 @c LaTeX to get the physical address of such a Lisp array:
958 @c LaTeX \begin{example}
959 @c LaTeX (defun array-data-address (array)
960 @c LaTeX "Return the physical address of where the actual data of an array is
963 @c LaTeX ARRAY must be a specialized array type in CMU Lisp. This means ARRAY
964 @c LaTeX must be an array of one of the following types:
966 @c LaTeX double-float
967 @c LaTeX single-float
968 @c LaTeX (unsigned-byte 32)
969 @c LaTeX (unsigned-byte 16)
970 @c LaTeX (unsigned-byte 8)
971 @c LaTeX (signed-byte 32)
972 @c LaTeX (signed-byte 16)
973 @c LaTeX (signed-byte 8)
975 @c LaTeX (declare (type (or #+signed-array (array (signed-byte 8))
976 @c LaTeX #+signed-array (array (signed-byte 16))
977 @c LaTeX #+signed-array (array (signed-byte 32))
978 @c LaTeX (array (unsigned-byte 8))
979 @c LaTeX (array (unsigned-byte 16))
980 @c LaTeX (array (unsigned-byte 32))
981 @c LaTeX (array single-float)
982 @c LaTeX (array double-float))
984 @c LaTeX (optimize (speed 3) (safety 0))
985 @c LaTeX (ext:optimize-interface (safety 3)))
986 @c LaTeX ;; with-array-data will get us to the actual data. However, because
987 @c LaTeX ;; the array could have been displaced, we need to know where the
988 @c LaTeX ;; data starts.
989 @c LaTeX (lisp::with-array-data ((data array)
992 @c LaTeX (declare (ignore end))
993 @c LaTeX ;; DATA is a specialized simple-array. Memory is laid out like this:
995 @c LaTeX ;; byte offset Value
996 @c LaTeX ;; 0 type code (should be 70 for double-float vector)
997 @c LaTeX ;; 4 4 * number of elements in vector
998 @c LaTeX ;; 8 1st element of vector
1001 @c LaTeX (let ((addr (+ 8 (logandc1 7 (kernel:get-lisp-obj-address data))))
1002 @c LaTeX (type-size (let ((type (array-element-type data)))
1003 @c LaTeX (cond ((or (equal type '(signed-byte 8))
1004 @c LaTeX (equal type '(unsigned-byte 8)))
1006 @c LaTeX ((or (equal type '(signed-byte 16))
1007 @c LaTeX (equal type '(unsigned-byte 16)))
1009 @c LaTeX ((or (equal type '(signed-byte 32))
1010 @c LaTeX (equal type '(unsigned-byte 32)))
1012 @c LaTeX ((equal type 'single-float)
1014 @c LaTeX ((equal type 'double-float)
1017 @c LaTeX (error "Unknown specialized array element type"))))))
1018 @c LaTeX (declare (type (unsigned-byte 32) addr)
1019 @c LaTeX (optimize (speed 3) (safety 0) (ext:inhibit-warnings 3)))
1020 @c LaTeX (system:int-sap (the (unsigned-byte 32)
1021 @c LaTeX (+ addr (* type-size start)))))))
1022 @c LaTeX \end{example}
1024 @c LaTeX Assume we have the C function below that we wish to use:
1025 @c LaTeX \begin{example}
1026 @c LaTeX double dotprod(double* x, double* y, int n)
1029 @c LaTeX double sum = 0;
1031 @c LaTeX for (k = 0; k < n; ++k) \{
1032 @c LaTeX sum += x[k] * y[k];
1035 @c LaTeX \end{example}
1036 @c LaTeX The following example generates two large arrays in Lisp, and calls the C
1037 @c LaTeX function to do the desired computation. This would not have been
1038 @c LaTeX possible using \code{malloc} or \code{make-alien} since we need about
1039 @c LaTeX 16 MB of memory to hold the two arrays.
1040 @c LaTeX \begin{example}
1041 @c LaTeX (define-alien-routine "dotprod" double
1042 @c LaTeX (x (* double-float) :in)
1043 @c LaTeX (y (* double-float) :in)
1044 @c LaTeX (n int :in))
1046 @c LaTeX (let ((x (make-array 1000000 :element-type 'double-float))
1047 @c LaTeX (y (make-array 1000000 :element-type 'double-float)))
1048 @c LaTeX ;; Initialize X and Y somehow
1049 @c LaTeX (let ((x-addr (system:int-sap (array-data-address x)))
1050 @c LaTeX (y-addr (system:int-sap (array-data-address y))))
1051 @c LaTeX (dotprod x-addr y-addr 1000000)))
1052 @c LaTeX \end{example}
1053 @c LaTeX In this example, it may be useful to wrap the inner \code{let}
1054 @c LaTeX expression in an \code{unwind-protect} that first turns off garbage
1055 @c LaTeX collection and then turns garbage collection on afterwards. This will
1056 @c LaTeX prevent garbage collection from moving \code{x} and \code{y} after we
1057 @c LaTeX have obtained the (now erroneous) addresses but before the call to
1058 @c LaTeX \code{dotprod} is made.
1063 @node Step-By-Step Example of the Foreign Function Interface
1064 @comment node-name, next, previous, up
1065 @section Step-By-Step Example of the Foreign Function Interface
1067 This section presents a complete example of an interface to a somewhat
1068 complicated C function.
1070 Suppose you have the following C function which you want to be able to
1071 call from Lisp in the file @file{test.c}
1080 struct c_struct *c_function (i, s, r, a)
1087 struct c_struct *r2;
1089 printf("i = %d\n", i);
1090 printf("s = %s\n", s);
1091 printf("r->x = %d\n", r->x);
1092 printf("r->s = %s\n", r->s);
1093 for (j = 0; j < 10; j++) printf("a[%d] = %d.\n", j, a[j]);
1094 r2 = (struct c_struct *) malloc (sizeof(struct c_struct));
1096 r2->s = "a C string";
1101 It is possible to call this C function from Lisp using the file
1102 @file{test.lisp} containing
1105 (cl:defpackage "TEST-C-CALL" (:use "CL" "SB-ALIEN" "SB-C-CALL"))
1106 (cl:in-package "TEST-C-CALL")
1108 ;;; Define the record C-STRUCT in Lisp.
1109 (define-alien-type nil
1114 ;;; Define the Lisp function interface to the C routine. It returns a
1115 ;;; pointer to a record of type C-STRUCT. It accepts four parameters:
1116 ;;; I, an int; S, a pointer to a string; R, a pointer to a C-STRUCT
1117 ;;; record; and A, a pointer to the array of 10 ints.
1119 ;;; The INLINE declaration eliminates some efficiency notes about heap
1120 ;;; allocation of alien values.
1121 (declaim (inline c-function))
1122 (define-alien-routine c-function
1123 (* (struct c-struct))
1126 (r (* (struct c-struct)))
1129 ;;; a function which sets up the parameters to the C function and
1130 ;;; actually calls it
1132 (with-alien ((ar (array int 10))
1133 (c-struct (struct c-struct)))
1134 (dotimes (i 10) ; Fill array.
1135 (setf (deref ar i) i))
1136 (setf (slot c-struct 'x) 20)
1137 (setf (slot c-struct 's) "a Lisp string")
1139 (with-alien ((res (* (struct c-struct))
1140 (c-function 5 "another Lisp string" (addr c-struct) ar)))
1141 (format t "~&back from C function~%")
1142 (multiple-value-prog1
1143 (values (slot res 'x)
1146 ;; Deallocate result. (after we are done referring to it:
1147 ;; "Pillage, *then* burn.")
1148 (free-alien res)))))
1151 To execute the above example, it is necessary to compile the C
1152 routine, e.g.: @samp{cc -c test.c && ld -shared -o test.so test.o} (In
1153 order to enable incremental loading with some linkers, you may need to
1154 say @samp{cc -G 0 -c test.c})
1156 Once the C code has been compiled, you can start up Lisp and load it in:
1157 @samp{sbcl}. Lisp should start up with its normal prompt.
1159 Within Lisp, compile the Lisp file. (This step can be done
1160 separately. You don't have to recompile every time.)
1161 @samp{(compile-file "test.lisp")}
1163 Within Lisp, load the foreign object file to define the necessary
1164 symbols: @samp{(load-shared-object "test.so")}.
1166 Now you can load the compiled Lisp (``fasl'') file into Lisp:
1167 @samp{(load "test.fasl")}
1168 And once the Lisp file is loaded, you can call the
1169 Lisp routine that sets up the parameters and calls the C
1171 @samp{(test-c-call::call-cfun)}
1173 The C routine should print the following information to standard output:
1177 s = another Lisp string
1179 r->s = a Lisp string
1192 After return from the C function,
1193 the Lisp wrapper function should print the following output:
1196 back from C function
1199 And upon return from the Lisp wrapper function,
1200 before the next prompt is printed, the
1201 Lisp read-eval-print loop should print the following return values: