| 1 |
@node Foreign Function Interface |
| 2 |
@section Foreign Function Interface |
| 3 |
@cindex Foreign function interface |
| 4 |
@ftindex FFI |
| 5 |
|
| 6 |
@menu |
| 7 |
* What is a FFI?:: FFI introduction |
| 8 |
* Two kinds of FFI:: ECL's FFI brief description |
| 9 |
* Foreign objects:: Handling the foreign objects |
| 10 |
* Higher level interfaces:: Usage examples |
| 11 |
* SFFI Reference:: Static FFI reference |
| 12 |
@c * LFFI Reference:: Library FFI reference /dlopen/ |
| 13 |
* DFFI Reference:: Dynamic FFI reference |
| 14 |
* UFFI Reference:: UFFI reference manual |
| 15 |
@end menu |
| 16 |
|
| 17 |
@node What is a FFI? |
| 18 |
@subsection What is a FFI? |
| 19 |
A Foreign Function Interface, or FFI for short, is a means for a programming language to |
| 20 |
interface with libraries written in other programming languages, the foreign code. You will |
| 21 |
see this concept most often being used in interpreted environments, such as Python, Ruby or |
| 22 |
Lisp, where one wants to reuse the big number of libraries written in C and C++ for dealing |
| 23 |
with graphical interfaces, networking, filesystems, etc. |
| 24 |
|
| 25 |
A FFI is made of at least three components: |
| 26 |
|
| 27 |
@table @dfn |
| 28 |
@item Foreign objects management |
| 29 |
This is the data that the foreign code will use. A FFI needs to provide |
| 30 |
means to build and manipulate foreign data, with automatic conversions |
| 31 |
to and from lisp data types whenever possible, and it also has to deal |
| 32 |
with issues like garbage collection and finalization. |
| 33 |
@item Foreign code loader |
| 34 |
To actually use a foreign routine, the code must reside in memory. The |
| 35 |
process of loading this code and finding out the addresses of the |
| 36 |
routines we want to use is normally done by an independent component. |
| 37 |
@item Foreign function invocation |
| 38 |
This is the part of the FFI that deals with actually calling the foreign |
| 39 |
routines we want to use. For that one typically has to tell the FFI what |
| 40 |
are the arguments that these routines expect, what are the calling |
| 41 |
conventions and where are these routines to be found. |
| 42 |
@end table |
| 43 |
|
| 44 |
On top of these components sits a higher level interface written |
| 45 |
entirely in lisp, with which you will actually declare and use foreign |
| 46 |
variables, functions and libraries. In the following sections we |
| 47 |
describe both the details of the low-level components (@xref{Two kinds |
| 48 |
of FFI} and @ref{Foreign objects}), and of the higher level interface |
| 49 |
(@xref{Higher level interfaces}). It is highly recommended that you read |
| 50 |
all sections. |
| 51 |
|
| 52 |
@node Two kinds of FFI |
| 53 |
@subsection Two kinds of FFI |
| 54 |
@cindex Two kinds of FFI |
| 55 |
ECL allows for two different approaches when building a FFI. Both |
| 56 |
approaches have a different implementation philosophy and affect the |
| 57 |
places where you can use the FFI and how. |
| 58 |
|
| 59 |
@table @dfn |
| 60 |
@item Static FFI (SFFI) |
| 61 |
For every foreign function and variable you might need to use, a wrapper |
| 62 |
is automatically written in C with the help of ffi:c-inline. These |
| 63 |
wrappers are compiled using an ordinary C compiler and linked against |
| 64 |
both the foreign libraries you want to use and against the ECL |
| 65 |
library. The result is a FASL file that can be loaded from ECL and where |
| 66 |
the wrappers appear as ordinary lisp functions and variables that the |
| 67 |
user may directly invoked. |
| 68 |
|
| 69 |
@c XXX: should we document DLOPEN from the FFI perspective here? |
| 70 |
@c @item Library FFI (LFFI) |
| 71 |
|
| 72 |
@item Dynamic FFI (DFFI) |
| 73 |
@cfindex --with-libffi-prefix=path |
| 74 |
@cfindex --with-dffi [system|included|AUTO|no] |
| 75 |
|
| 76 |
First of all, the foreign libraries are loaded in memory using the |
| 77 |
facilities of the operating system. Similar routines are used to find |
| 78 |
out and register the memory location of all the functions and variables |
| 79 |
we want to use. Finally, when actually accessing these functions, a |
| 80 |
little piece of assembly code does the job of translating the lisp data |
| 81 |
into foreign objects, storing the arguments in the stack and in CPU |
| 82 |
registers, calling the function and converting back the output of the |
| 83 |
function to lisp. |
| 84 |
|
| 85 |
ECL for this purpose utilizes |
| 86 |
@emph{@uref{https://sourceware.org/libffi/, libffi}}, a portable |
| 87 |
foreign-function interface library. |
| 88 |
@end table |
| 89 |
|
| 90 |
@float Figure,fig:ffi_components |
| 91 |
@caption{FFI components} |
| 92 |
@image{figures/ffi,,1.5in} |
| 93 |
@end float |
| 94 |
|
| 95 |
As you see, the first approach uses rather portable techniques based on a |
| 96 |
programming language (C, C++) which is strongly supported by the |
| 97 |
operating system. The conversion of data is performed by a calling |
| 98 |
routines in the ECL library and we need not care about the precise |
| 99 |
details (organizing the stack, CPU registers, etc) when calling a |
| 100 |
function: the compiler does this for us. |
| 101 |
|
| 102 |
On the other hand, the dynamic approach allows us to choose the |
| 103 |
libraries we load at any time, look for the functions and invoke them |
| 104 |
even from the toplevel, but it relies on unportable techniques and |
| 105 |
requires the developers to know very well both the assembly code of the |
| 106 |
machine the code runs on and the calling conventions of that particular |
| 107 |
operating system. For these reasons ECL doesn't maintain it's own |
| 108 |
implementation of the DFFI but rather relies on the third party library. |
| 109 |
|
| 110 |
ECL currently supports the static method on all platforms, and the |
| 111 |
dynamical one a wide range of the most popular ones, shown in the |
| 112 |
section @emph{Supported Platforms} at |
| 113 |
@url{https://sourceware.org/libffi/}. |
| 114 |
|
| 115 |
@ftindex DFFI |
| 116 |
You can test if your copy of ECL was built with DFFI by inspecting |
| 117 |
whether the symbol @code{:dffi} is present in the list from variable |
| 118 |
@code{*features*}. |
| 119 |
|
| 120 |
@node Foreign objects |
| 121 |
@subsection Foreign objects |
| 122 |
|
| 123 |
While the foreign function invocation protocols differ strongly between |
| 124 |
platforms and implementations, foreign objects are pretty easy to handle |
| 125 |
portably. For ECL, a foreign object is just a bunch of bytes stored in |
| 126 |
memory. The lisp object for a foreign object encapsulates several bits |
| 127 |
of information: |
| 128 |
|
| 129 |
@itemize @bullet |
| 130 |
@item |
| 131 |
A list or a symbol specifying the C type of the object. |
| 132 |
@item |
| 133 |
The pointer to the region of memory where data is stored. |
| 134 |
@item |
| 135 |
A flag determining whether ECL can automatically manage that piece of |
| 136 |
memory and deallocated when no longer in use. |
| 137 |
@end itemize |
| 138 |
|
| 139 |
A foreign object may contain many different kinds of data: integers, |
| 140 |
floating point numbers, C structures, unions, etc. The actual type of |
| 141 |
the object is stored in a list or a symbol which is understood by the |
| 142 |
higher level interface (@xref{Higher level interfaces}). |
| 143 |
|
| 144 |
The most important component of the object is the memory region where |
| 145 |
data is stored. By default ECL assumes that the user will perform |
| 146 |
manual management of this memory, deleting the object when it is no |
| 147 |
longer needed. The first reason is that this block may have been |
| 148 |
allocated by a foreign routine using @code{malloc()}, or |
| 149 |
@code{mmap()}, or statically, by referring to a C constant. The second |
| 150 |
reason is that foreign functions may store references to this memory |
| 151 |
which ECL is not aware of and, in order to keep these references |
| 152 |
valid, ECL should not attempt to automatically destroy the object. |
| 153 |
|
| 154 |
In many cases, however, it is desirable to automatically destroy foreign |
| 155 |
objects once they have been used. The higher level interfaces UFFI and |
| 156 |
@url{https://common-lisp.net/project/cffi/,CFFI} provide tools for doing |
| 157 |
this. For instance, in the following example adapted from the UFFI |
| 158 |
documentation, the string @var{name} is automatically deallocated |
| 159 |
|
| 160 |
@lisp |
| 161 |
(ffi:def-function ("gethostname" c-gethostname) |
| 162 |
((name (* :unsigned-char)) |
| 163 |
(len :int)) |
| 164 |
:returning :int) |
| 165 |
|
| 166 |
(ffi:with-foreign-object (name '(:array :unsigned-char 256)) |
| 167 |
(if (zerop (c-gethostname (ffi:char-array-to-pointer name) 256)) |
| 168 |
(format t "Hostname: ~S" (ffi:convert-from-foreign-string name)) |
| 169 |
(error "gethostname() failed."))) |
| 170 |
@end lisp |
| 171 |
|
| 172 |
@subsubsection C Reference |
| 173 |
|
| 174 |
@cppindex ecl_make_pointer |
| 175 |
@cppdef ecl_make_foreign_data |
| 176 |
@deftypefun cl_object ecl_make_foreign_data (cl_object tag, cl_index size, void *data) |
| 177 |
|
| 178 |
@paragraph Description |
| 179 |
This function creates a Lisp ``foreign object'' that points to a C data. Use |
| 180 |
this function to pass a data from C to Lisp. |
| 181 |
|
| 182 |
@var{tag} denotes the data type (@xref{Primitive Types}) |
| 183 |
@var{size} is a number of elements in @var{data} (or 0 for a raw pointer) |
| 184 |
@var{data} is a pointer to C data (either an object or an array) |
| 185 |
|
| 186 |
The C macro @code{ecl_make_pointer(pointer)} expands to |
| 187 |
@code{ecl_make_foreign_data(ECL_NIL, 0, (pointer))}. |
| 188 |
@end deftypefun |
| 189 |
|
| 190 |
@cppdef ecl_to_pointer |
| 191 |
@cppdef ecl_foreign_data_pointer_safe |
| 192 |
@deftypefun void *ecl_foreign_data_pointer_safe(cl_object f) |
| 193 |
|
| 194 |
@paragraph Description |
| 195 |
This function returns a C pointer for the given Lisp foreign object. Lisp |
| 196 |
foreign objects are constructed with functions @code{ecl_make_foreign_data} |
| 197 |
and @code{ecl_allocate_foreign_data}. |
| 198 |
|
| 199 |
The wrapper created with @code{ecl_make_foreign_data} is a subject of |
| 200 |
garbage collection, but the pointer itself is not ``freed'', because |
| 201 |
the data producer is ``C world'' and the consumer is ``Lisp world''. |
| 202 |
|
| 203 |
This is different from @code{si:allocate-foreign-object} where the |
| 204 |
data producer is ``Lisp world'' and the consumer is ``C world''. In |
| 205 |
that case the wrapper is not collected unless explicitly released with |
| 206 |
@code{si:free-foreign-object} in which case the allocated foreign data |
| 207 |
is also released. |
| 208 |
@end deftypefun |
| 209 |
|
| 210 |
@cppdef ecl_base_string_pointer_safe |
| 211 |
|
| 212 |
@deftypefun char *ecl_base_string_pointer_safe(cl_object f) |
| 213 |
|
| 214 |
@paragraph Description |
| 215 |
This function returns a pointer to a simple base string @var{f}. If @var{f} is |
| 216 |
not a simple base string this function signals an error. |
| 217 |
|
| 218 |
@end deftypefun |
| 219 |
|
| 220 |
@cppdef ecl_null_terminated_base_string |
| 221 |
@deftypefun cl_object ecl_null_terminated_base_string(cl_object s) |
| 222 |
|
| 223 |
@paragraph Description |
| 224 |
Tries to coerce a string to a simple base string suitable for |
| 225 |
@code{ecl_base_string_pointer_safe}. This function may cons data. |
| 226 |
|
| 227 |
@end deftypefun |
| 228 |
|
| 229 |
@c FIXME these functions operate on the enum ecl_ffi_tag but other functions |
| 230 |
@c operate on keyword tags (see ecl_make_foreign_data). Also both functions |
| 231 |
@c are part of the exported interface, but conversion keyword->ecl_ffi_tag is |
| 232 |
@c done by the function ecl_foreign_type_code that is declared in internal.h. |
| 233 |
@c |
| 234 |
@c Do one of either: |
| 235 |
@c 1. move ecl_foreign_data_*_elt to internal.h |
| 236 |
@c 2. move ecl_foreign_type_code from internal.h to external.h |
| 237 |
@c 3. document the ecl_ffi_tag enum and change the ecl_make_foreign_data |
| 238 |
@c 4. change functions ecl_foreign_data_*_elt to work on tags |
| 239 |
@c |
| 240 |
@c The cleanest solution will be 4. Perhaps to remain backward compatible with |
| 241 |
@c people who used ecl_foreign_data_*_elt we should make these two C macros |
| 242 |
@c and expand to a new function interface using tags. Until this is fixed |
| 243 |
@c let's not advertise these functions in the documentation. -- jd 2021-11-22 |
| 244 |
|
| 245 |
@c @cppdef ecl_foreign_data_ref_elt |
| 246 |
@c @cppdef ecl_foreign_data_set_elt |
| 247 |
@c @deftypefun cl_object ecl_foreign_data_ref_elt(void *p, enum ecl_ffi_tag tag) |
| 248 |
@c @deftypefunx cl_object ecl_foreign_data_set_elt(void *p, enum ecl_ffi_tag tag, cl_object value) |
| 249 |
|
| 250 |
@c @paragraph Description |
| 251 |
@c These functions are used to operate directly on C data in @var{p}. |
| 252 |
@c The referenced C object is coerced to a Lisp type and returned. |
| 253 |
@c The Lisp value that is set to C object is coerced to a C type. |
| 254 |
|
| 255 |
@c @end deftypefun |
| 256 |
|
| 257 |
@node Higher level interfaces |
| 258 |
@subsection Higher level interfaces |
| 259 |
Up to now we have only discussed vague ideas about how a FFI works, but you are probably more |
| 260 |
interested on how to actually code all these things in lisp. You have here three |
| 261 |
possibilities: |
| 262 |
|
| 263 |
@itemize @bullet |
| 264 |
@item |
| 265 |
ECL supplies a high level interface which is compatible with UFFI up to |
| 266 |
version 1.8 (api for >=v2.0 is provided by cffi-uffi-compat system |
| 267 |
shipped with CFFI). Code designed for UFFI library should run mostly |
| 268 |
unchanged with ECL. Note, that api resides in ffi package, not uffi, to |
| 269 |
prevent conflicts with cffi-uffi-compat. New code shouldn't use this |
| 270 |
interface preferring @url{https://common-lisp.net/project/cffi/,CFFI}. |
| 271 |
@item |
| 272 |
The @url{https://common-lisp.net/project/cffi/,CFFI} library features a |
| 273 |
complete backend for ECL. This method of interfacing with the foreign |
| 274 |
libraries is preferred over using UFFI. |
| 275 |
@item |
| 276 |
ECL's own low level interface. Only to be used if ECL is your deployment |
| 277 |
platform. It features some powerful constructs that allow you to mix |
| 278 |
arbitrary C and lisp code. |
| 279 |
@end itemize |
| 280 |
|
| 281 |
In the following two subsections we will discuss two practical examples of using the native |
| 282 |
UFFI and the CFFI library. |
| 283 |
|
| 284 |
@c XXX: we should describe here, how to use SFFI for interactive C/C++ development |
| 285 |
@c @node Lower level interfaces |
| 286 |
|
| 287 |
@subsubheading UFFI example |
| 288 |
@exindex UFFI usage |
| 289 |
|
| 290 |
The example below shows how to use UFFI in an application. There are several important |
| 291 |
ingredients: |
| 292 |
|
| 293 |
@itemize @bullet |
| 294 |
@item |
| 295 |
You need to specify the libraries you use and do it at the toplevel, so |
| 296 |
that the compiler may include them at link time. |
| 297 |
@item |
| 298 |
Every function you will use has to be declared using |
| 299 |
@coderef{ffi:def-function}. |
| 300 |
@item |
| 301 |
In the cases of headers not used by ECL, a header to include might need |
| 302 |
to be specified using @coderef{ffi:clines}. |
| 303 |
@end itemize |
| 304 |
|
| 305 |
@lisp |
| 306 |
#| |
| 307 |
Build and load this module with (compile-file "uffi.lsp" :load t) |
| 308 |
|# |
| 309 |
;; |
| 310 |
;; This toplevel statement notifies the compiler that we will |
| 311 |
;; need this shared library at runtime. We do not need this |
| 312 |
;; statement in windows or modern macOS. |
| 313 |
;; The actually needed path to libm might be different on different systems. |
| 314 |
;; |
| 315 |
#-(or ming32 windows darwin) |
| 316 |
(ffi:load-foreign-library "/usr/lib/libm.so") |
| 317 |
;; |
| 318 |
;; With this other statement, we import the C function sin(), |
| 319 |
;; which operates on IEEE doubles. |
| 320 |
;; |
| 321 |
(ffi:def-function ("sin" c-sin) ((arg :double)) |
| 322 |
:returning :double) |
| 323 |
;; |
| 324 |
;; We now use this function and compare with the lisp version. |
| 325 |
;; |
| 326 |
(format t "~%Lisp sin:~t~d~%C sin:~t~d~%Difference:~t~d" |
| 327 |
(sin 1.0d0) (c-sin 1.0d0) (- (sin 1.0d0) (c-sin 1.0d0))) |
| 328 |
@end lisp |
| 329 |
|
| 330 |
@subsubheading CFFI example |
| 331 |
@exindex CFFI usage |
| 332 |
|
| 333 |
The @url{https://common-lisp.net/project/cffi/,CFFI} library is an |
| 334 |
independent project and it is not shipped with ECL. If you wish to use |
| 335 |
it you can go to their homepage, download the code and build it using |
| 336 |
ASDF. |
| 337 |
|
| 338 |
CFFI differs slightly from UFFI in that functions may be used even |
| 339 |
without being declared beforehand. |
| 340 |
|
| 341 |
@lisp |
| 342 |
#| |
| 343 |
Build and load this module with (compile-file "cffi.lsp" :load t) |
| 344 |
|# |
| 345 |
;; |
| 346 |
;; This toplevel statement notifies the compiler that we will |
| 347 |
;; need this shared library at runtime. We do not need this |
| 348 |
;; statement in windows or macOS. |
| 349 |
;; |
| 350 |
#-(or ming32 windows darwin) |
| 351 |
(cffi:load-foreign-library "/usr/lib/libm.so") |
| 352 |
;; |
| 353 |
;; With this other statement, we import the C function sin(), |
| 354 |
;; which operates on IEEE doubles. |
| 355 |
;; |
| 356 |
(cffi:defcfun ("sin" c-sin) :double '(:double)) |
| 357 |
;; |
| 358 |
;; We now use this function and compare with the lisp version. |
| 359 |
;; |
| 360 |
(format t "~%Lisp sin:~t~d~%C sin:~t~d~%Difference:~t~d" |
| 361 |
(sin 1.0d0) (c-sin 1.0d0) (- (sin 1.0d0) (c-sin 1.0d0))) |
| 362 |
;; |
| 363 |
;; The following also works: no declaration! |
| 364 |
;; |
| 365 |
(let ((c-cos (cffi:foreign-funcall "cos" :double 1.0d0 :double))) |
| 366 |
(format t "~%Lisp cos:~t~d~%C cos:~t~d~%Difference:~t~d" |
| 367 |
(cos 1.0d0) c-cos (- (cos 1.0d0) c-cos))) |
| 368 |
@end lisp |
| 369 |
|
| 370 |
@subsubheading SFFI example (low level inlining) |
| 371 |
@exindex SFFI usage |
| 372 |
|
| 373 |
To compare with the previous pieces of code, we show how the previous programs would be |
| 374 |
written using @coderef{ffi:clines} and @coderef{ffi:c-inline}. |
| 375 |
|
| 376 |
@lisp |
| 377 |
#| |
| 378 |
Build and load this module with (compile-file "ecl.lsp" :load t) |
| 379 |
|# |
| 380 |
;; |
| 381 |
;; With this other statement, we import the C function sin(), which |
| 382 |
;; operates on IEEE doubles. Notice that we include the C header to |
| 383 |
;; get the full declaration. |
| 384 |
;; |
| 385 |
(defun c-sin (x) |
| 386 |
(ffi:clines "#include <math.h>") |
| 387 |
(ffi:c-inline (x) (:double) :double "sin(#0)" :one-liner t)) |
| 388 |
;; |
| 389 |
;; We now use this function and compare with the lisp version. |
| 390 |
;; |
| 391 |
(format t "~%Lisp sin:~t~d~%C sin:~t~d~%Difference:~t~d" |
| 392 |
(sin 1.0d0) (c-sin 1.0d0) (- (sin 1.0d0) (c-sin 1.0d0))) |
| 393 |
@end lisp |
| 394 |
|
| 395 |
@include extensions/ffi_sffi.txi |
| 396 |
@include extensions/ffi_dffi.txi |
| 397 |
@include extensions/ffi_uffi.txi |