Interfacing with Other Languages
While many useful libraries can be written in “pure” Common Lisp using only the features specified in the language standard, and many more can be written in Lisp using nonstandard facilities provided by a given implementation, occasionally it’s more straightforward to use an existing library written in another language, such as C.
The language standard doesn’t specify a mechanism for Lisp code to call code written in another language or even require that implementations provide such a mechanism. But these days, almost all Common Lisp implementations support what’s called a Foreign Function Interface, or FFI for short.2 The basic job of an FFI is to allow you to give Lisp enough information to be able to link in the foreign code. Thus, if you’re going to call a function from a C library, you need to tell Lisp about how to translate the Lisp objects passed to the function into C types and the value returned by the function back into a Lisp object. However, each implementation provides its own FFI, each with slightly varying capabilities and syntax. Some FFIs allow callbacks from C to Lisp, and others don’t. The Universal Foreign Function Interface (UFFI) project provides a portability layer over the FFIs of more than a half dozen different Common Lisp implementations. It works by defining its own macros that expand into appropriate FFI code for the implementation it’s running in. The UFFI takes a lowest common denominator approach, which means it can’t take advantage of all the features of different implementations’ FFIs, but it does provide a good way to build a simple Lisp wrapper around a basic C API.3