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