Chapter 5. The Foreign Function Interface

Table of Contents

Introduction to the Foreign Function Interface
Foreign Types
Defining Foreign Types
Foreign Types and Lisp Types
Foreign Type Specifiers
Operations On Foreign Values
Accessing Foreign Values
Coercing Foreign Values
Foreign Dynamic Allocation
Foreign Variables
Local Foreign Variables
External Foreign Variables
Foreign Data Structure Examples
Loading Unix Object Files
Foreign Function Calls
The alien-funcall Primitive
The define-alien-routine Macro
define-alien-routine Example
Calling Lisp From C
Step-By-Step Example of the Foreign Function Interface

This chapter describes SBCL's interface to C programs and libraries (and, since C interfaces are a sort of lingua franca of the Unix world, to other programs and libraries in general.)

Note

In the modern Lisp world, the usual term for this functionality is Foreign Function Interface, or FFI, where despite the mention of “function” in this term, FFI also refers to direct manipulation of C data structures as well as functions. The traditional CMU CL terminology is Alien Interface, and while that older terminology is no longer used much in the system documentation, it still reflected in names in the implementation, notably in the name of the SB-ALIEN package.

Because of Lisp's emphasis on dynamic memory allocation and garbage collection, Lisp implementations use non-C-like memory representations for objects. This representation mismatch creates friction when a Lisp program must share objects with programs which expect C data. There are three common approaches to establishing communication:

SBCL, like CMU CL before it, relies primarily on the automatic conversion and direct manipulation approaches. The SB-ALIEN package provices a facility wherein foreign values of simple scalar types are automatically converted and complex types are directly manipulated in their foreign representation. Additionally the lower-level System Area Pointers (or SAPs) can be used where necessary to provide untyped access to foreign memory.

Any foreign objects that can't automatically be converted into Lisp values are represented by objects of type alien-value. Since Lisp is a dynamically typed language, even foreign objects must have a run-time type; this type information is provided by encapsulating the raw pointer to the foreign data within an alien-value object.

The type language and operations on foreign types are intentionally similar to those of the C language.