Chapter 3. Foreign Function Interface

3.1. What is a FFI?
3.2. Two kinds of FFI
3.3. Foreign objects
3.4. Higher level interfaces
3.4.1. UFFI example
3.4.2. CFFI example
3.4.3. Low level example
3.5. FFI Reference
ffi:clines — Insert C declarations and definitions
ffi:c-inline — Inline C code in a lisp form.

3.1. What is a FFI?

A Foreign Function Interface, or FFI for short, is a means for a programming language to interface with libraries written in other programming languages, the foreign code. You will see this concept most often being used in interpreted environments, such as Python, Ruby or Lisp, where one wants to reuse the big number of libraries written in C and C++ for dealing with graphical interfaces, networking, filesystems, etc.

A FFI is made of at least three components:

Foreign objects management

This is the data that the foreign code will use. A FFI needs to provide means to buid and manipulate foreign data, with automatic conversions to and from lisp data types whenever possible, and it also has to deal with issues like garbage collection and finalization.

Foreign code loader

To actually use a foreign routine, the code must reside in memory. The process of loading this code and finding out the addresses of the routines we want to use is normally done by an independent component.

Foreign function invocation

This is the part of the FFI that deals with actually calling the foreign routines we want to use. For that one typically has to tell the FFI what are the arguments that these routines expect, what are the calling conventions and where are these routines to be found.

On top of these components sits a higher level interface written entirely in lisp, with which you will actually declare and use foreign variables, functions and libraries. In the following sections we describe both the details of the low-level components (Section 3.2, Section 3.3), and of the higher level interface (Section 3.4). It is highly recommended that you read all sections.