1 \input texinfo @c -*- Mode: Texinfo; Mode: auto-fill -*-
4 @settitle CFFI User Manual
7 @c @documentencoding utf-8
11 @c * The reference section names and "See Also" list are roman, not
12 @c @code. This is to follow the format of CLHS.
14 @c * How it looks in HTML is the priority.
16 @c ============================= Macros =============================
17 @c The following macros are used throughout this manual.
19 @macro Function {args}
29 @macro Accessor {args}
30 @deffn {Accessor} \args\
34 @macro GenericFunction {args}
35 @deffn {Generic Function} \args\
39 @macro ForeignType {args}
40 @deftp {Foreign Type} \args\
44 @macro Variable {args}
45 @defvr {Special Variable} \args\
49 @macro Condition {args}
50 @deftp {Condition Type} \args\
60 @strong{Implementor's note:} @emph{\text\}
64 @c Info "requires" that x-refs end in a period or comma, or ) in the
65 @c case of @pxref. So the following implements that requirement for
66 @c the "See also" subheadings that permeate this manual, but only in
78 @c Typeset comments in roman font for the TeX output.
88 @c ============================= Macros =============================
91 @c Show types, functions, and concepts in the same index.
96 Copyright @copyright{} 2005 James Bielman <jamesjb at jamesjb.com> @*
97 Copyright @copyright{} 2005-2015 Lu@'{@dotless{i}}s Oliveira
98 <loliveira at common-lisp.net> @*
99 Copyright @copyright{} 2005-2006 Dan Knapp <danka at accela.net> @*
100 Copyright @copyright{} 2005-2006 Emily Backes <lucca at accela.net> @*
101 Copyright @copyright{} 2006 Stephen Compall <s11 at member.fsf.org>
104 Permission is hereby granted, free of charge, to any person obtaining
105 a copy of this software and associated documentation files (the
106 ``Software''), to deal in the Software without restriction, including
107 without limitation the rights to use, copy, modify, merge, publish,
108 distribute, sublicense, and/or sell copies of the Software, and to
109 permit persons to whom the Software is furnished to do so, subject to
110 the following conditions:
112 The above copyright notice and this permission notice shall be
113 included in all copies or substantial portions of the Software.
115 @sc{The software is provided ``as is'', without warranty of any kind,
116 express or implied, including but not limited to the warranties of
117 merchantability, fitness for a particular purpose and noninfringement.
118 In no event shall the authors or copyright holders be liable for any
119 claim, damages or other liability, whether in an action of contract,
120 tort or otherwise, arising from, out of or in connection with the
121 software or the use or other dealings in the software.}
126 @dircategory Software development
128 * CFFI Manual: (cffi-manual). CFFI Manual.
132 @title CFFI User Manual
133 @c @subtitle Version X.X
134 @c @author James Bielman
137 @vskip 0pt plus 1filll
144 @node Top, Introduction, (dir), (dir)
150 * Introduction:: What is CFFI?
152 * Implementation Support::
153 * Tutorial:: Interactive intro to using CFFI.
154 * Wrapper generators:: CFFI forms from munging C source code.
165 * Platform-specific features:: Details about the underlying system.
166 * Glossary:: List of CFFI-specific terms and meanings.
167 * Comprehensive Index::
174 * convert-from-foreign:: Outside interface to backward type translator.
175 * convert-to-foreign:: Outside interface to forward type translator.
176 * defbitfield:: Defines a bitfield.
177 * defcstruct:: Defines a C structure type.
178 * defcunion:: Defines a C union type.
179 * defctype:: Defines a foreign typedef.
180 * defcenum:: Defines a C enumeration.
181 * define-foreign-type:: Defines a foreign type specifier.
182 * define-parse-method:: Specifies how a type should be parsed.
183 @c * explain-foreign-slot-value:: <unimplemented>
184 * foreign-bitfield-symbols:: Returns a list of symbols for a bitfield type.
185 * foreign-bitfield-value:: Calculates a value for a bitfield type.
186 * foreign-enum-keyword:: Finds a keyword in an enum type.
187 * foreign-enum-value:: Finds a value in an enum type.
188 * foreign-slot-names:: Returns a list of slot names in a foreign struct.
189 * foreign-slot-offset:: Returns the offset of a slot in a foreign struct.
190 * foreign-slot-pointer:: Returns a pointer to a slot in a foreign struct.
191 * foreign-slot-value:: Returns the value of a slot in a foreign struct.
192 * foreign-type-alignment:: Returns the alignment of a foreign type.
193 * foreign-type-size:: Returns the size of a foreign type.
194 * free-converted-object:: Outside interface to typed object deallocators.
195 * free-translated-object:: Defines how to free a oreign object.
196 * translate-from-foreign:: Defines a foreign-to-Lisp object translation.
197 * translate-to-foreign:: Defines a Lisp-to-foreign object translation.
198 * with-foreign-object:: Allocates a foreign object with dynamic extent.
199 * with-foreign-objects:: Plural form of @code{with-foreign-object}.
200 * with-foreign-slots:: Accesses the slots of a foreign structure.
204 * foreign-free:: Deallocates memory.
205 * foreign-alloc:: Allocates memory.
206 * foreign-symbol-pointer:: Returns a pointer to a foreign symbol.
207 * inc-pointer:: Increments the address held by a pointer.
208 * incf-pointer:: Increments the pointer address in a place.
209 * make-pointer:: Returns a pointer to a given address.
210 * mem-aptr:: The pointer to an element of an array.
211 * mem-aref:: Accesses the value of an index in an array.
212 * mem-ref:: Dereferences a pointer.
213 * null-pointer:: Returns a NULL pointer.
214 * null-pointer-p:: Tests a pointer for NULL value.
215 * pointerp:: Tests whether an object is a pointer or not.
216 * pointer-address:: Returns the address pointed to by a pointer.
217 * pointer-eq:: Tests if two pointers point to the same address.
218 * with-foreign-pointer:: Allocates memory with dynamic extent.
222 * *default-foreign-encoding*:: Default encoding for the string types.
223 * foreign-string-alloc:: Converts a Lisp string to a foreign string.
224 * foreign-string-free:: Deallocates memory used by a foreign string.
225 * foreign-string-to-lisp:: Converts a foreign string to a Lisp string.
226 * lisp-string-to-foreign:: Copies a Lisp string into a foreign string.
227 * with-foreign-string:: Allocates a foreign string with dynamic extent.
228 * with-foreign-strings:: Plural form of @code{with-foreign-string}.
229 * with-foreign-pointer-as-string:: Similar to CL's with-output-to-string.
233 * defcvar:: Defines a C global variable.
234 * get-var-pointer:: Returns a pointer to a defined global variable.
238 * defcfun:: Defines a foreign function.
239 * foreign-funcall:: Performs a call to a foreign function.
240 * foreign-funcall-pointer:: Performs a call through a foreign pointer.
241 * translate-camelcase-name:: Converts a camelCase foreign name to/from a Lisp name.
242 * translate-name-from-foreign:: Converts a foreign name to a Lisp name.
243 * translate-name-to-foreign:: Converts a Lisp name to a foreign name.
244 * translate-underscore-separated-name:: Converts an underscore_separated foreign name to/from a Lisp name.
248 * close-foreign-library:: Closes a foreign library.
249 * *darwin-framework-directories*:: Search path for Darwin frameworks.
250 * define-foreign-library:: Explain how to load a foreign library.
251 * *foreign-library-directories*:: Search path for shared libraries.
252 * load-foreign-library:: Load a foreign library.
253 * load-foreign-library-error:: Signalled on failure of its namesake.
254 @c * reload-foreign-libraries:: Reload foreign libraries.
255 * use-foreign-library:: Load a foreign library when needed.
259 * callback:: Returns a pointer to a defined callback.
260 * defcallback:: Defines a Lisp callback.
261 * get-callback:: Returns a pointer to a defined callback.
269 @c ===================================================================
270 @c CHAPTER: Introduction
272 @node Introduction, Installation, Top, Top
273 @chapter Introduction
275 @cffi{} is the Common Foreign Function Interface for @acronym{ANSI}
276 Common Lisp systems. By @dfn{foreign function} we mean a function
277 written in another programming language and having different data and
278 calling conventions than Common Lisp, namely, C. @cffi{} allows you
279 to call foreign functions and access foreign variables, all without
280 leaving the Lisp image.
282 We consider this manual ever a work in progress. If you have
283 difficulty with anything @cffi{}-specific presented in the manual,
284 please contact @email{cffi-devel@@common-lisp.net,the developers} with
290 @xref{Tutorial-Comparison,, What makes Lisp different}, for
291 an argument in favor of @acronym{FFI} in general.
293 @cffi{}'s primary role in any image is to mediate between Lisp
294 developers and the widely varying @acronym{FFI}s present in the
295 various Lisp implementations it supports. With @cffi{}, you can
296 define foreign function interfaces while still maintaining portability
297 between implementations. It is not the first Common Lisp package with
298 this objective; however, it is meant to be a more malleable framework
299 than similar packages.
302 @heading Design Philosophy
306 Pointers do not carry around type information. Instead, type
307 information is supplied when pointers are dereferenced.
310 A type safe pointer interface can be developed on top of an
311 untyped one. It is difficult to do the opposite.
314 Functions are better than macros. When a macro could be used
315 for performance, use a compiler-macro instead.
319 @c ===================================================================
320 @c CHAPTER: Installation
322 @node Installation, Implementation Support, Introduction, Top
323 @chapter Installation
325 @cffi{} can be obtained through one of the following means available
326 through its @uref{http://common-lisp.net/project/cffi/,,website}:
330 @uref{http://common-lisp.net/project/cffi/releases/?M=D,,official release
334 @uref{http://common-lisp.net/gitweb?p=projects/cffi/cffi.git,,git
337 @c snapshots have been disabled as of
339 @c @uref{http://common-lisp.net/project/cffi/tarballs/?M=D,,nightly-generated
344 In addition, you will need to obtain and install the following
349 @uref{http://common-lisp.net/project/babel/,,Babel}, a charset
350 encoding/decoding library.
353 @uref{http://common-lisp.net/project/alexandria/,,Alexandria}, a
354 collection of portable public-domain utilities.
357 @uref{http://www.cliki.net/trivial-features,,trivial-features}, a
358 portability layer that ensures consistent @code{*features*} across
359 multiple Common Lisp implementations.
363 Furthermore, if you wish to run the testsuite,
364 @uref{http://www.cliki.net/rt,,RT} is required.
366 You may find mechanisms such as
367 @uref{https://www.quicklisp.org/beta/,Quicklisp} (recommended)
368 or @uref{http://common-lisp.net/project/clbuild/,,clbuild} (for advanced
369 uses) helpful in getting and managing @cffi{} and its
373 @c ===================================================================
374 @c CHAPTER: Implementation Support
376 @node Implementation Support, Tutorial, Installation, Top
377 @chapter Implementation Support
379 @cffi{} supports various free and commercial Lisp implementations:
380 @acronym{ABCL}, Allegro CL, Clasp, @sc{clisp}, Clozure CL,
381 @acronym{CMUCL}, Corman CL, @acronym{ECL}, @acronym{GCL}, LispWorks,
382 @acronym{MCL}, @acronym{SBCL} and the Scieneer CL.
384 In general, you should work with the latest versions of each
385 implementation since those will usually be tested against recent
386 versions of CFFI more often and might include necessary features or
387 bug fixes. Reasonable patches for compatibility with earlier versions
388 are welcome nevertheless.
392 Some features are not supported in all implementations.
393 @c TODO: describe these features here.
394 @c flat-namespace too
396 @subheading Allegro CL
400 Does not support the @code{:long-long} type natively.
402 Unicode support is limited to the Basic Multilingual Plane (16-bit
410 Only supports a flat namespace.
417 No Unicode support. (8-bit code points)
420 @subheading Corman CL
424 Does not support @code{foreign-funcall}.
427 @subheading @acronym{ECL}
431 On platforms where ECL's dynamic FFI is not supported (ie. when
432 @code{:dffi} is not present in @code{*features*}),
433 @code{cffi:load-foreign-library} does not work and you must use ECL's
434 own @code{ffi:load-foreign-library} with a constant string argument.
437 @subheading Lispworks
441 Does not completely support the @code{:long-long} type natively in
444 Unicode support is limited to the Basic Multilingual Plane (16-bit
448 @subheading @acronym{SBCL}
452 Not all platforms support callbacks.
457 @c ===================================================================
458 @c CHAPTER: An Introduction to Foreign Interfaces and CFFI
460 @c This macro is merely a marker that I don't think I'll use after
462 @macro tutorialsource {text}
466 @c because I don't want to type this over and over
468 http://www.cliki.net/CFFI
470 @c TeX puts spurious newlines in when you use the above macro
471 @c in @examples &c. So it is expanded below in some places.
474 @node Tutorial, Wrapper generators, Implementation Support, Top
475 @chapter An Introduction to Foreign Interfaces and @acronym{CFFI}
477 @c Above, I don't use the cffi macro because it breaks TeX.
479 @cindex tutorial, @cffi{}
480 Users of many popular languages bearing semantic similarity to Lisp,
481 such as Perl and Python, are accustomed to having access to popular C
482 libraries, such as @acronym{GTK}, by way of ``bindings''. In Lisp, we
483 do something similar, but take a fundamentally different approach.
484 This tutorial first explains this difference, then explains how you
485 can use @cffi{}, a powerful system for calling out to C and C++ and
486 access C data from many Common Lisp implementations.
488 @cindex foreign functions and data
489 The concept can be generalized to other languages; at the time of
490 writing, only @cffi{}'s C support is fairly complete. Therefore, we
491 will interchangeably refer to @dfn{foreign functions} and @dfn{foreign
492 data}, and ``C functions'' and ``C data''. At no time will the word
493 ``foreign'' carry its usual, non-programming meaning.
495 This tutorial expects you to have a working understanding of both
496 Common Lisp and C, including the Common Lisp macro system.
499 * Tutorial-Comparison:: Why FFI?
500 * Tutorial-Getting a URL:: An FFI use case.
501 * Tutorial-Loading:: Load libcurl.so.
502 * Tutorial-Initializing:: Call a function in libcurl.so.
503 * Tutorial-easy_setopt:: An advanced libcurl function.
504 * Tutorial-Abstraction:: Why breaking it is necessary.
505 * Tutorial-Lisp easy_setopt:: Semi-Lispy option interface.
506 * Tutorial-Memory:: In C, you collect the garbage.
507 * Tutorial-Callbacks:: Make useful C function pointers.
508 * Tutorial-Completion:: Minimal get-url functionality.
509 * Tutorial-Types:: Defining new foreign types.
510 * Tutorial-Conclusion:: What's next?
514 @node Tutorial-Comparison, Tutorial-Getting a URL, Tutorial, Tutorial
515 @section What makes Lisp different
517 The following sums up how bindings to foreign libraries are usually
518 implemented in other languages, then in Common Lisp:
521 @item Perl, Python, Java, other one-implementation languages
522 @cindex @acronym{SWIG}
525 Bindings are implemented as shared objects written in C. In some
526 cases, the C code is generated by a tool, such as @acronym{SWIG}, but
527 the result is the same: a new C library that manually translates
528 between the language implementation's objects, such as @code{PyObject}
529 in Python, and whatever C object is called for, often using C
530 functions provided by the implementation. It also translates between
531 the calling conventions of the language and C.
534 @cindex @acronym{SLIME}
535 Bindings are written in Lisp. They can be created at-will by Lisp
536 programs. Lisp programmers can write new bindings and add them to the
537 image, using a listener such as @acronym{SLIME}, as easily as with
538 regular Lisp definitions. The only foreign library to load is the one
539 being wrapped---the one with the pure C interface; no C or other
540 non-Lisp compilation is required.
543 @cindex advantages of @acronym{FFI}
544 @cindex benefits of @acronym{FFI}
545 We believe the advantages of the Common Lisp approach far outweigh any
546 disadvantages. Incremental development with a listener can be as
547 productive for C binding development as it is with other Lisp
548 development. Keeping it ``in the [Lisp] family'', as it were, makes
549 it much easier for you and other Lisp programmers to load and use the
550 bindings. Common Lisp implementations such as @acronym{CMUCL}, freed
551 from having to provide a C interface to their own objects, are thus
552 freed to be implemented in another language (as @acronym{CMUCL} is)
553 while still allowing programmers to call foreign functions.
555 @cindex minimal bindings
556 Perhaps the greatest advantage is that using an @acronym{FFI} doesn't
557 obligate you to become a professional binding developer. Writers of
558 bindings for other languages usually end up maintaining or failing to
559 maintain complete bindings to the foreign library. Using an
560 @acronym{FFI}, however, means if you only need one or two functions,
561 you can write bindings for only those functions, and be assured that
562 you can just as easily add to the bindings if need be.
564 @cindex C abstractions
565 @cindex abstractions in C
566 The removal of the C compiler, or C interpretation of any kind,
567 creates the main disadvantage: some of C's ``abstractions'' are not
568 available, violating information encapsulation. For example,
569 @code{struct}s that must be passed on the stack, or used as return
570 values, without corresponding functional abstractions to create and
571 manage the @code{struct}s, must be declared explicitly in Lisp. This
572 is fine for structs whose contents are ``public'', but is not so
573 pleasant when a struct is supposed to be ``opaque'' by convention,
574 even though it is not so defined.@footnote{Admittedly, this is an
575 advanced issue, and we encourage you to leave this text until you are
576 more familiar with how @cffi{} works.}
578 Without an abstraction to create the struct, Lisp needs to be able to
579 lay out the struct in memory, so must know its internal details.
581 @cindex workaround for C
582 In these cases, you can create a minimal C library to provide the
583 missing abstractions, without destroying all the advantages of the
584 Common Lisp approach discussed above. In the case of @code{struct}s,
585 you can write simple, pure C functions that tell you how many bytes a
586 struct requires or allocate new structs, read and write fields of the
587 struct, or whatever operations are supposed to be
588 public.@footnote{This does not apply to structs whose contents are
589 intended to be part of the public library interface. In those cases,
590 a pure Lisp struct definition is always preferred. In fact, many
591 prefer to stay in Lisp and break the encapsulation anyway, placing the
592 burden of correct library interface definition on the library.}
593 @ref{The Groveller} automates this and other processes.
595 Another disadvantage appears when you would rather use the foreign
596 language than Lisp. However, someone who prefers C to Lisp is not a
597 likely candidate for developing a Lisp interface to a C library.
600 @node Tutorial-Getting a URL, Tutorial-Loading, Tutorial-Comparison, Tutorial
601 @section Getting a @acronym{URL}
603 @cindex c@acronym{URL}
604 The widely available @code{libcurl} is a library for downloading files
605 over protocols like @acronym{HTTP}. We will use @code{libcurl} with
606 @cffi{} to download a web page.
608 Please note that there are many other ways to download files from the
609 web, not least the @sc{cl-curl} project to provide bindings to
610 @code{libcurl} via a similar @acronym{FFI}.@footnote{Specifically,
611 @acronym{UFFI}, an older @acronym{FFI} that takes a somewhat different
612 approach compared to @cffi{}. I believe that these days (December
613 2005) @cffi{} is more portable and actively developed, though not as
614 mature yet. Consensus in the free @sc{unix} Common Lisp community
615 seems to be that @cffi{} is preferred for new development, though
616 @acronym{UFFI} will likely go on for quite some time as many projects
617 already use it. @cffi{} includes the @code{UFFI-COMPAT} package for
618 complete compatibility with @acronym{UFFI}.}
620 @uref{http://curl.haxx.se/libcurl/c/libcurl-tutorial.html,,libcurl-tutorial(3)}
621 is a tutorial for @code{libcurl} programming in C. We will follow
622 that to develop a binding to download a file. We will also use
623 @file{curl.h}, @file{easy.h}, and the @command{man} pages for the
624 @code{libcurl} function, all available in the @samp{curl-dev} package
625 or equivalent for your system, or in the c@acronym{URL} source code
626 package. If you have the development package, the headers should be
627 installed in @file{/usr/include/curl/}, and the @command{man} pages
628 may be accessed through your favorite @command{man} facility.
631 @node Tutorial-Loading, Tutorial-Initializing, Tutorial-Getting a URL, Tutorial
632 @section Loading foreign libraries
634 @cindex loading @cffi{}
635 @cindex requiring @cffi{}
636 First of all, we will create a package to work in. You can save these
637 forms in a file, or just send them to the listener as they are. If
638 creating bindings for an @acronym{ASDF} package of yours, you will
639 want to add @code{:cffi} to the @code{:depends-on} list in your
640 @file{.asd} file. Otherwise, just use the @code{asdf:load-system} function to
643 @tutorialsource{Initialization}
645 (asdf:load-system :cffi)
647 ;;; @lispcmt{Nothing special about the "CFFI-USER" package. We're just}
648 ;;; @lispcmt{using it as a substitute for your own CL package.}
649 (defpackage :cffi-user
650 (:use :common-lisp :cffi))
652 (in-package :cffi-user)
654 (define-foreign-library libcurl
655 (:darwin (:or "libcurl.3.dylib" "libcurl.dylib"))
656 (:unix (:or "libcurl.so.3" "libcurl.so"))
657 (t (:default "libcurl")))
659 (use-foreign-library libcurl)
662 @cindex foreign library load
663 @cindex library, foreign
664 Using @code{define-foreign-library} and @code{use-foreign-library}, we
665 have loaded @code{libcurl} into Lisp, much as the linker does when you
666 start a C program, or @code{common-lisp:load} does with a Lisp source
667 file or @acronym{FASL} file. We special-cased for @sc{unix} machines
668 to always load a particular version, the one this tutorial was tested
669 with; for those who don't care, the @code{define-foreign-library}
670 clause @code{(t (:default "libcurl"))} should be satisfactory, and
671 will adapt to various operating systems.
674 @node Tutorial-Initializing, Tutorial-easy_setopt, Tutorial-Loading, Tutorial
675 @section Initializing @code{libcurl}
677 @cindex function definition
678 After the introductory matter, the tutorial goes on to present the
679 first function you should use.
682 CURLcode curl_global_init(long flags);
686 Let's pick this apart into appropriate Lisp code:
688 @tutorialsource{First CURLcode}
690 ;;; @lispcmt{A CURLcode is the universal error code. curl/curl.h says}
691 ;;; @lispcmt{no return code will ever be removed, and new ones will be}
692 ;;; @lispcmt{added to the end.}
693 (defctype curl-code :int)
695 ;;; @lispcmt{Initialize libcurl with FLAGS.}
696 (defcfun "curl_global_init" curl-code
700 @impnote{By default, CFFI assumes the UNIX viewpoint that there is one
701 C symbol namespace, containing all symbols in all loaded objects.
702 This is not so on Windows and Darwin, but we emulate UNIX's behaviour
703 there. @ref{defcfun} for more details.}
705 Note the parallels with the original C declaration. We've defined
706 @code{curl-code} as a wrapping type for @code{:int}; right now, it
707 only marks it as special, but later we will do something more
708 interesting with it. The point is that we don't have to do it yet.
710 @cindex calling foreign functions
711 Looking at @file{curl.h}, @code{CURL_GLOBAL_NOTHING}, a possible value
712 for @code{flags} above, is defined as @samp{0}. So we can now call
716 @sc{cffi-user>} (curl-global-init 0)
720 @cindex looks like it worked
721 Looking at @file{curl.h} again, @code{0} means @code{CURLE_OK}, so it
722 looks like the call succeeded. Note that @cffi{} converted the
723 function name to a Lisp-friendly name. You can specify your own name
724 if you want; use @code{("curl_global_init" @var{your-name-here})} as
725 the @var{name} argument to @code{defcfun}.
727 The tutorial goes on to have us allocate a handle. For good measure,
728 we should also include the deallocator. Let's look at these
732 CURL *curl_easy_init( );
733 void curl_easy_cleanup(CURL *handle);
736 Advanced users may want to define special pointer types; we will
737 explore this possibility later. For now, just treat every pointer as
740 @tutorialsource{curl_easy handles}
742 (defcfun "curl_easy_init" :pointer)
744 (defcfun "curl_easy_cleanup" :void
745 (easy-handle :pointer))
748 Now we can continue with the tutorial:
751 @sc{cffi-user>} (defparameter *easy-handle* (curl-easy-init))
752 @result{} *EASY-HANDLE*
753 @sc{cffi-user>} *easy-handle*
754 @result{} #<FOREIGN-ADDRESS #x09844EE0>
757 @cindex pointers in Lisp
758 Note the print representation of a pointer. It changes depending on
759 what Lisp you are using, but that doesn't make any difference to
763 @node Tutorial-easy_setopt, Tutorial-Abstraction, Tutorial-Initializing, Tutorial
764 @section Setting download options
766 The @code{libcurl} tutorial says we'll want to set many options before
767 performing any download actions. This is done through
768 @code{curl_easy_setopt}:
770 @c That is literally ..., not an ellipsis.
772 CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
776 @cindex foreign arguments
777 We've introduced a new twist: variable arguments. There is no obvious
778 translation to the @code{defcfun} form, particularly as there are four
779 possible argument types. Because of the way C works, we could define
780 four wrappers around @code{curl_easy_setopt}, one for each type; in
781 this case, however, we'll use the general-purpose macro
782 @code{foreign-funcall} to call this function.
784 @cindex enumeration, C
785 To make things easier on ourselves, we'll create an enumeration of the
786 kinds of options we want to set. The @code{enum CURLoption} isn't the
787 most straightforward, but reading the @code{CINIT} C macro definition
788 should be enlightening.
790 @tutorialsource{CURLoption enumeration}
792 (defmacro define-curl-options (name type-offsets &rest enum-args)
793 "As with CFFI:DEFCENUM, except each of ENUM-ARGS is as follows:
797 Where the arguments are as they are with the CINIT macro defined
798 in curl.h, except NAME is a keyword.
800 TYPE-OFFSETS is a plist of TYPEs to their integer offsets, as
801 defined by the CURLOPTTYPE_LONG et al constants in curl.h."
802 (flet ((enumerated-value (type offset)
803 (+ (getf type-offsets type) offset)))
806 ,@@(loop for (name type number) in enum-args
807 collect (list name (enumerated-value type number))))
808 ',name))) ;@lispcmt{for REPL users' sanity}
810 (define-curl-options curl-option
811 (long 0 objectpoint 10000 functionpoint 20000 off-t 30000)
812 (:noprogress long 43)
814 (:errorbuffer objectpoint 10)
815 (:url objectpoint 2))
818 With some well-placed Emacs @code{query-replace-regexp}s, you could
819 probably similarly define the entire @code{CURLoption} enumeration. I
820 have selected to transcribe a few that we will use in this tutorial.
822 If you're having trouble following the macrology, just macroexpand the
823 @code{curl-option} definition, or see the following macroexpansion,
824 conveniently downcased and reformatted:
826 @tutorialsource{DEFINE-CURL-OPTIONS macroexpansion}
829 (defcenum curl-option
838 That seems more than reasonable. You may notice that we only use the
839 @var{type} to compute the real enumeration offset; we will also need
840 the type information later.
842 First, however, let's make sure a simple call to the foreign function
846 @sc{cffi-user>} (foreign-funcall "curl_easy_setopt"
847 :pointer *easy-handle*
848 curl-option :nosignal :long 1 curl-code)
852 @code{foreign-funcall}, despite its surface simplicity, can be used to
853 call any C function. Its first argument is a string, naming the
854 function to be called. Next, for each argument, we pass the name of
855 the C type, which is the same as in @code{defcfun}, followed by a Lisp
856 object representing the data to be passed as the argument. The final
857 argument is the return type, for which we use the @code{curl-code}
858 type defined earlier.
860 @code{defcfun} just puts a convenient fa@,cade on
861 @code{foreign-funcall}.@footnote{This isn't entirely true; some Lisps
862 don't support @code{foreign-funcall}, so @code{defcfun} is implemented
863 without it. @code{defcfun} may also perform optimizations that
864 @code{foreign-funcall} cannot.} Our earlier call to
865 @code{curl-global-init} could have been written as follows:
868 @sc{cffi-user>} (foreign-funcall "curl_global_init" :long 0
873 Before we continue, we will take a look at what @cffi{} can and can't
874 do, and why this is so.
877 @node Tutorial-Abstraction, Tutorial-Lisp easy_setopt, Tutorial-easy_setopt, Tutorial
878 @section Breaking the abstraction
880 @cindex breaking the abstraction
881 @cindex abstraction breaking
882 In @ref{Tutorial-Comparison,, What makes Lisp different}, we mentioned
883 that writing an @acronym{FFI} sometimes requires depending on
884 information not provided as part of the interface. The easy option
885 @code{CURLOPT_WRITEDATA}, which we will not provide as part of the
886 Lisp interface, illustrates this issue.
888 Strictly speaking, the @code{curl-option} enumeration is not
889 necessary; we could have used @code{:int 99} instead of
890 @code{curl-option :nosignal} in our call to @code{curl_easy_setopt}
891 above. We defined it anyway, in part to hide the fact that we are
892 breaking the abstraction that the C @code{enum} provides. If the
893 c@acronym{URL} developers decide to change those numbers later, we
894 must change the Lisp enumeration, because enumeration values are not
895 provided in the compiled C library, @code{libcurl.so.3}.
897 @cffi{} works because the most useful things in C libraries ---
898 non-static functions and non-static variables --- are included
899 accessibly in @code{libcurl.so.3}. A C compiler that violated this
900 would be considered a worthless compiler.
902 The other thing @code{define-curl-options} does is give the ``type''
903 of the third argument passed to @code{curl_easy_setopt}. Using this
904 information, we can tell that the @code{:nosignal} option should
905 accept a long integer argument. We can implicitly assume @code{t}
906 @equiv{} 1 and @code{nil} @equiv{} 0, as it is in C, which takes care
907 of the fact that @code{CURLOPT_NOSIGNAL} is really asking for a
910 The ``type'' of @code{CURLOPT_WRITEDATA} is @code{objectpoint}.
911 However, it is really looking for a @code{FILE*}.
912 @code{CURLOPT_ERRORBUFFER} is looking for a @code{char*}, so there is
913 no obvious @cffi{} type but @code{:pointer}.
915 The first thing to note is that nowhere in the C interface includes
916 this information; it can only be found in the manual. We could
917 disjoin these clearly different types ourselves, by splitting
918 @code{objectpoint} into @code{filepoint} and @code{charpoint}, but we
919 are still breaking the abstraction, because we have to augment the
920 entire enumeration form with this additional
921 information.@footnote{Another possibility is to allow the caller to
922 specify the desired C type of the third argument. This is essentially
923 what happens in a call to the function written in C.}
925 @cindex streams and C
926 @cindex @sc{file}* and streams
927 The second is that the @code{CURLOPT_WRITEDATA} argument is completely
928 incompatible with the desired Lisp data, a
929 stream.@footnote{@xref{Other Kinds of Streams,,, libc, GNU C Library
930 Reference}, for a @acronym{GNU}-only way to extend the @code{FILE*}
931 type. You could use this to convert Lisp streams to the needed C
932 data. This would be quite involved and far outside the scope of this
933 tutorial.} It is probably acceptable if we are controlling every file
934 we might want to use as this argument, in which case we can just call
935 the foreign function @code{fopen}. Regardless, though, we can't write
936 to arbitrary streams, which is exactly what we want to do for this
939 Finally, note that the @code{curl_easy_setopt} interface itself is a
940 hack, intended to work around some of the drawbacks of C. The
941 definition of @code{Curl_setopt}, while long, is far less cluttered
942 than the equivalent disjoint-function set would be; in addition,
943 setting a new option in an old @code{libcurl} can generate a run-time
944 error rather than breaking the compile. Lisp can just as concisely
945 generate functions as compare values, and the ``undefined function''
946 error is just as useful as any explicit error we could define here
950 @node Tutorial-Lisp easy_setopt, Tutorial-Memory, Tutorial-Abstraction, Tutorial
951 @section Option functions in Lisp
953 We could use @code{foreign-funcall} directly every time we wanted to
954 call @code{curl_easy_setopt}. However, we can encapsulate some of the
955 necessary information with the following.
958 ;;; @lispcmt{We will use this type later in a more creative way. For}
959 ;;; @lispcmt{now, just consider it a marker that this isn't just any}
960 ;;; @lispcmt{pointer.}
961 (defctype easy-handle :pointer)
963 (defmacro curl-easy-setopt (easy-handle enumerated-name
964 value-type new-value)
965 "Call `curl_easy_setopt' on EASY-HANDLE, using ENUMERATED-NAME
966 as the OPTION. VALUE-TYPE is the CFFI foreign type of the third
967 argument, and NEW-VALUE is the Lisp data to be translated to the
968 third argument. VALUE-TYPE is not evaluated."
969 `(foreign-funcall "curl_easy_setopt" easy-handle ,easy-handle
970 curl-option ,enumerated-name
971 ,value-type ,new-value curl-code))
974 Now we define a function for each kind of argument that encodes the
975 correct @code{value-type} in the above. This can be done reasonably
976 in the @code{define-curl-options} macroexpansion; after all, that is
977 where the different options are listed!
979 @cindex Lispy C functions
980 We could make @code{cl:defun} forms in the expansion that simply call
981 @code{curl-easy-setopt}; however, it is probably easier and clearer to
982 use @code{defcfun}. @code{define-curl-options} was becoming unwieldy,
983 so I defined some helpers in this new definition.
986 (defun curry-curl-option-setter (function-name option-keyword)
987 "Wrap the function named by FUNCTION-NAME with a version that
988 curries the second argument as OPTION-KEYWORD.
990 This function is intended for use in DEFINE-CURL-OPTION-SETTER."
991 (setf (symbol-function function-name)
992 (let ((c-function (symbol-function function-name)))
993 (lambda (easy-handle new-value)
994 (funcall c-function easy-handle option-keyword
997 (defmacro define-curl-option-setter (name option-type
998 option-value foreign-type)
999 "Define (with DEFCFUN) a function NAME that calls
1000 curl_easy_setopt. OPTION-TYPE and OPTION-VALUE are the CFFI
1001 foreign type and value to be passed as the second argument to
1002 easy_setopt, and FOREIGN-TYPE is the CFFI foreign type to be used
1003 for the resultant function's third argument.
1005 This macro is intended for use in DEFINE-CURL-OPTIONS."
1007 (defcfun ("curl_easy_setopt" ,name) curl-code
1008 (easy-handle easy-handle)
1009 (option ,option-type)
1010 (new-value ,foreign-type))
1011 (curry-curl-option-setter ',name ',option-value)))
1013 (defmacro define-curl-options (type-name type-offsets &rest enum-args)
1014 "As with CFFI:DEFCENUM, except each of ENUM-ARGS is as follows:
1018 Where the arguments are as they are with the CINIT macro defined
1019 in curl.h, except NAME is a keyword.
1021 TYPE-OFFSETS is a plist of TYPEs to their integer offsets, as
1022 defined by the CURLOPTTYPE_LONG et al constants in curl.h.
1024 Also, define functions for each option named
1025 set-`TYPE-NAME'-`OPTION-NAME', where OPTION-NAME is the NAME from
1026 the above destructuring."
1027 (flet ((enumerated-value (type offset)
1028 (+ (getf type-offsets type) offset))
1029 ;; @lispcmt{map PROCEDURE, destructuring each of ENUM-ARGS}
1030 (map-enum-args (procedure)
1031 (mapcar (lambda (arg) (apply procedure arg)) enum-args))
1032 ;; @lispcmt{build a name like SET-CURL-OPTION-NOSIGNAL}
1033 (make-setter-name (option-name)
1034 (intern (concatenate
1035 'string "SET-" (symbol-name type-name)
1036 "-" (symbol-name option-name)))))
1038 (defcenum ,type-name
1040 (lambda (name type number)
1041 (list name (enumerated-value type number)))))
1043 (lambda (name type number)
1044 (declare (ignore number))
1045 `(define-curl-option-setter ,(make-setter-name name)
1046 ,type-name ,name ,(ecase type
1048 (objectpoint :pointer)
1049 (functionpoint :pointer)
1055 Macroexpanding our @code{define-curl-options} form once more, we
1056 see something different:
1060 (defcenum curl-option
1063 (:errorbuffer 10010)
1065 (define-curl-option-setter set-curl-option-noprogress
1066 curl-option :noprogress :long)
1067 (define-curl-option-setter set-curl-option-nosignal
1068 curl-option :nosignal :long)
1069 (define-curl-option-setter set-curl-option-errorbuffer
1070 curl-option :errorbuffer :pointer)
1071 (define-curl-option-setter set-curl-option-url
1072 curl-option :url :pointer)
1077 Macroexpanding one of the new @code{define-curl-option-setter}
1078 forms yields the following:
1082 (defcfun ("curl_easy_setopt" set-curl-option-nosignal) curl-code
1083 (easy-handle easy-handle)
1084 (option curl-option)
1086 (curry-curl-option-setter 'set-curl-option-nosignal ':nosignal))
1090 Finally, let's try this out:
1093 @sc{cffi-user>} (set-curl-option-nosignal *easy-handle* 1)
1098 Looks like it works just as well. This interface is now reasonably
1099 high-level to wash out some of the ugliness of the thinnest possible
1100 @code{curl_easy_setopt} @acronym{FFI}, without obscuring the remaining
1101 C bookkeeping details we will explore.
1104 @node Tutorial-Memory, Tutorial-Callbacks, Tutorial-Lisp easy_setopt, Tutorial
1105 @section Memory management
1107 According to the documentation for @code{curl_easy_setopt}, the type
1108 of the third argument when @var{option} is @code{CURLOPT_ERRORBUFFER}
1109 is @code{char*}. Above, we've defined
1110 @code{set-curl-option-errorbuffer} to accept a @code{:pointer} as the
1111 new option value. However, there is a @cffi{} type @code{:string},
1112 which translates Lisp strings to C strings when passed as arguments to
1113 foreign function calls. Why not, then, use @code{:string} as the
1114 @cffi{} type of the third argument? There are two reasons, both
1115 related to the necessity of breaking abstraction described in
1116 @ref{Tutorial-Abstraction,, Breaking the abstraction}.
1118 The first reason also applies to @code{CURLOPT_URL}, which we will use
1119 to illustrate the point. Assuming we have changed the type of the
1120 third argument underlying @code{set-curl-option-url} to
1121 @code{:string}, look at these two equivalent forms.
1124 (set-curl-option-url *easy-handle* "http://www.cliki.net/CFFI")
1126 @equiv{} (with-foreign-string (url "http://www.cliki.net/CFFI")
1127 (foreign-funcall "curl_easy_setopt" easy-handle *easy-handle*
1128 curl-option :url :pointer url curl-code))
1132 The latter, in fact, is mostly equivalent to what a foreign function
1133 call's macroexpansion actually does. As you can see, the Lisp string
1134 @code{"@clikicffi{}"} is copied into a @code{char} array and
1135 null-terminated; the pointer to beginning of this array, now a C
1136 string, is passed as a @cffi{} @code{:pointer} to the foreign
1139 @cindex dynamic extent
1140 @cindex foreign values with dynamic extent
1141 Unfortunately, the C abstraction has failed us, and we must break it.
1142 While @code{:string} works well for many @code{char*} arguments, it
1143 does not for cases like this. As the @code{curl_easy_setopt}
1144 documentation explains, ``The string must remain present until curl no
1145 longer needs it, as it doesn't copy the string.'' The C string
1146 created by @code{with-foreign-string}, however, only has dynamic
1147 extent: it is ``deallocated'' when the body (above containing the
1148 @code{foreign-funcall} form) exits.
1150 @cindex premature deallocation
1151 If we are supposed to keep the C string around, but it goes away, what
1152 happens when some @code{libcurl} function tries to access the
1153 @acronym{URL} string? We have reentered the dreaded world of C
1154 ``undefined behavior''. In some Lisps, it will probably get a chunk
1155 of the Lisp/C stack. You may segfault. You may get some random piece
1156 of other data from the heap. Maybe, in a world where ``dynamic
1157 extent'' is defined to be ``infinite extent'', everything will turn
1158 out fine. Regardless, results are likely to be almost universally
1159 unpleasant.@footnote{``@i{But I thought Lisp was supposed to protect
1160 me from all that buggy C crap!}'' Before asking a question like that,
1161 remember that you are a stranger in a foreign land, whose residents
1162 have a completely different set of values.}
1164 Returning to the current @code{set-curl-option-url} interface, here is
1170 (with-foreign-string (url "http://www.cliki.net/CFFI")
1171 (setf easy-handle (curl-easy-init))
1172 (set-curl-option-url easy-handle url)
1173 #|@lispcmt{do more with the easy-handle, like actually get the URL}|#)
1175 (curl-easy-cleanup easy-handle))))
1178 @c old comment to luis: I go on to say that this isn't obviously
1179 @c extensible to new option settings that require C strings to stick
1180 @c around, as it would involve re-evaluating the unwind-protect form
1181 @c with more dynamic memory allocation. So I plan to show how to
1182 @c write something similar to ObjC's NSAutoreleasePool, to be managed
1183 @c with a simple unwind-protect form.
1186 That is fine for the single string defined here, but for every string
1187 option we want to pass, we have to surround the body of
1188 @code{with-foreign-string} with another @code{with-foreign-string}
1189 wrapper, or else do some extremely error-prone pointer manipulation
1190 and size calculation in advance. We could alleviate some of the pain
1191 with a recursively expanding macro, but this would not remove the need
1192 to modify the block every time we want to add an option, anathema as
1193 it is to a modular interface.
1195 Before modifying the code to account for this case, consider the other
1196 reason we can't simply use @code{:string} as the foreign type. In C,
1197 a @code{char *} is a @code{char *}, not necessarily a string. The
1198 option @code{CURLOPT_ERRORBUFFER} accepts a @code{char *}, but does
1199 not expect anything about the data there. However, it does expect
1200 that some @code{libcurl} function we call later can write a C string
1201 of up to 255 characters there. We, the callers of the function, are
1202 expected to read the C string at a later time, exactly the opposite of
1203 what @code{:string} implies.
1205 With the semantics for an input string in mind --- namely, that the
1206 string should be kept around until we @code{curl_easy_cleanup} the
1207 easy handle --- we are ready to extend the Lisp interface:
1210 (defvar *easy-handle-cstrings* (make-hash-table)
1211 "Hashtable of easy handles to lists of C strings that may be
1212 safely freed after the handle is freed.")
1214 (defun make-easy-handle ()
1215 "Answer a new CURL easy interface handle, to which the lifetime
1216 of C strings may be tied. See `add-curl-handle-cstring'."
1217 (let ((easy-handle (curl-easy-init)))
1218 (setf (gethash easy-handle *easy-handle-cstrings*) '())
1221 (defun free-easy-handle (handle)
1222 "Free CURL easy interface HANDLE and any C strings created to
1224 (curl-easy-cleanup handle)
1225 (mapc #'foreign-string-free
1226 (gethash handle *easy-handle-cstrings*))
1227 (remhash handle *easy-handle-cstrings*))
1229 (defun add-curl-handle-cstring (handle cstring)
1230 "Add CSTRING to be freed when HANDLE is, answering CSTRING."
1231 (car (push cstring (gethash handle *easy-handle-cstrings*))))
1235 Here we have redefined the interface to create and free handles, to
1236 associate a list of allocated C strings with each handle while it
1237 exists. The strategy of using different function names to wrap around
1238 simple foreign functions is more common than the solution implemented
1239 earlier with @code{curry-curl-option-setter}, which was to modify the
1240 function name's function slot.@footnote{There are advantages and
1241 disadvantages to each approach; I chose to @code{(setf
1242 symbol-function)} earlier because it entailed generating fewer magic
1245 Incidentally, the next step is to redefine
1246 @code{curry-curl-option-setter} to allocate C strings for the
1247 appropriate length of time, given a Lisp string as the
1248 @code{new-value} argument:
1251 (defun curry-curl-option-setter (function-name option-keyword)
1252 "Wrap the function named by FUNCTION-NAME with a version that
1253 curries the second argument as OPTION-KEYWORD.
1255 This function is intended for use in DEFINE-CURL-OPTION-SETTER."
1256 (setf (symbol-function function-name)
1257 (let ((c-function (symbol-function function-name)))
1258 (lambda (easy-handle new-value)
1259 (funcall c-function easy-handle option-keyword
1260 (if (stringp new-value)
1261 (add-curl-handle-cstring
1263 (foreign-string-alloc new-value))
1268 A quick analysis of the code shows that you need only reevaluate the
1269 @code{curl-option} enumeration definition to take advantage of these
1270 new semantics. Now, for good measure, let's reallocate the handle
1271 with the new functions we just defined, and set its @acronym{URL}:
1274 @sc{cffi-user>} (curl-easy-cleanup *easy-handle*)
1276 @sc{cffi-user>} (setf *easy-handle* (make-easy-handle))
1277 @result{} #<FOREIGN-ADDRESS #x09844EE0>
1278 @sc{cffi-user>} (set-curl-option-nosignal *easy-handle* 1)
1280 @sc{cffi-user>} (set-curl-option-url *easy-handle*
1281 "http://www.cliki.net/CFFI")
1286 For fun, let's inspect the Lisp value of the C string that was created
1287 to hold @code{"@clikicffi{}"}. By virtue of the implementation of
1288 @code{add-curl-handle-cstring}, it should be accessible through the
1292 @sc{cffi-user>} (foreign-string-to-lisp
1293 (car (gethash *easy-handle* *easy-handle-cstrings*)))
1294 @result{} "http://www.cliki.net/CFFI"
1298 Looks like that worked, and @code{libcurl} now knows what
1299 @acronym{URL} we want to retrieve.
1301 Finally, we turn back to the @code{:errorbuffer} option mentioned at
1302 the beginning of this section. Whereas the abstraction added to
1303 support string inputs works fine for cases like @code{CURLOPT_URL}, it
1304 hides the detail of keeping the C string; for @code{:errorbuffer},
1305 however, we need that C string.
1307 In a moment, we'll define something slightly cleaner, but for now,
1308 remember that you can always hack around anything. We're modifying
1309 handle creation, so make sure you free the old handle before
1310 redefining @code{free-easy-handle}.
1313 (defvar *easy-handle-errorbuffers* (make-hash-table)
1314 "Hashtable of easy handles to C strings serving as error
1315 writeback buffers.")
1317 ;;; @lispcmt{An extra byte is very little to pay for peace of mind.}
1318 (defparameter *curl-error-size* 257
1319 "Minimum char[] size used by cURL to report errors.")
1321 (defun make-easy-handle ()
1322 "Answer a new CURL easy interface handle, to which the lifetime
1323 of C strings may be tied. See `add-curl-handle-cstring'."
1324 (let ((easy-handle (curl-easy-init)))
1325 (setf (gethash easy-handle *easy-handle-cstrings*) '())
1326 (setf (gethash easy-handle *easy-handle-errorbuffers*)
1327 (foreign-alloc :char :count *curl-error-size*
1328 :initial-element 0))
1331 (defun free-easy-handle (handle)
1332 "Free CURL easy interface HANDLE and any C strings created to
1334 (curl-easy-cleanup handle)
1335 (foreign-free (gethash handle *easy-handle-errorbuffers*))
1336 (remhash handle *easy-handle-errorbuffers*)
1337 (mapc #'foreign-string-free
1338 (gethash handle *easy-handle-cstrings*))
1339 (remhash handle *easy-handle-cstrings*))
1341 (defun get-easy-handle-error (handle)
1342 "Answer a string containing HANDLE's current error message."
1343 (foreign-string-to-lisp
1344 (gethash handle *easy-handle-errorbuffers*)))
1347 Be sure to once again set the options we've set thus far. You may
1348 wish to define yet another wrapper function to do this.
1351 @node Tutorial-Callbacks, Tutorial-Completion, Tutorial-Memory, Tutorial
1352 @section Calling Lisp from C
1354 If you have been reading
1355 @uref{http://curl.haxx.se/libcurl/c/curl_easy_setopt.html,,
1356 @code{curl_easy_setopt(3)}}, you should have noticed that some options
1357 accept a function pointer. In particular, we need one function
1358 pointer to set as @code{CURLOPT_WRITEFUNCTION}, to be called by
1359 @code{libcurl} rather than the reverse, in order to receive data as it
1362 A binding writer without the aid of @acronym{FFI} usually approaches
1363 this problem by writing a C function that accepts C data, converts to
1364 the language's internal objects, and calls the callback provided by
1365 the user, again in a reverse of usual practices.
1367 The @cffi{} approach to callbacks precisely mirrors its differences
1368 with the non-@acronym{FFI} approach on the ``calling C from Lisp''
1369 side, which we have dealt with exclusively up to now. That is, you
1370 define a callback function in Lisp using @code{defcallback}, and
1371 @cffi{} effectively creates a C function to be passed as a function
1374 @impnote{This is much trickier than calling C functions from Lisp, as
1375 it literally involves somehow generating a new C function that is as
1376 good as any created by the compiler. Therefore, not all Lisps support
1377 them. @xref{Implementation Support}, for information about @cffi{}
1378 support issues in this and other areas. You may want to consider
1379 changing to a Lisp that supports callbacks in order to continue with
1382 @cindex callback definition
1383 @cindex defining callbacks
1384 Defining a callback is very similar to defining a callout; the main
1385 difference is that we must provide some Lisp forms to be evaluated as
1386 part of the callback. Here is the signature for the function the
1387 @code{:writefunction} option takes:
1391 @var{function}(void *ptr, size_t size, size_t nmemb, void *stream);
1394 @impnote{size_t is almost always an unsigned int. You can get this
1395 and many other types using feature tests for your system by using
1398 The above signature trivially translates into a @cffi{}
1399 @code{defcallback} form, as follows.
1402 ;;; @lispcmt{Alias in case size_t changes.}
1403 (defctype size :unsigned-int)
1405 ;;; @lispcmt{To be set as the CURLOPT_WRITEFUNCTION of every easy handle.}
1406 (defcallback easy-write size ((ptr :pointer) (size size)
1407 (nmemb size) (stream :pointer))
1408 (let ((data-size (* size nmemb)))
1410 ;; @lispcmt{We use the dynamically-bound *easy-write-procedure* to}
1411 ;; @lispcmt{call a closure with useful lexical context.}
1412 (progn (funcall (symbol-value '*easy-write-procedure*)
1413 (foreign-string-to-lisp ptr :count data-size))
1414 data-size) ;@lispcmt{indicates success}
1415 ;; @lispcmt{The WRITEFUNCTION should return something other than the}
1416 ;; @lispcmt{#bytes available to signal an error.}
1417 (error () (if (zerop data-size) 1 0)))))
1420 First, note the correlation of the first few forms, used to declare
1421 the C function's signature, with the signature in C syntax. We
1422 provide a Lisp name for the function, its return type, and a name and
1423 type for each argument.
1425 In the body, we call the dynamically-bound
1426 @code{*easy-write-procedure*} with a ``finished'' translation, of
1427 pulling together the raw data and size into a Lisp string, rather than
1428 deal with the data directly. As part of calling
1429 @code{curl_easy_perform} later, we'll bind that variable to a closure
1430 with more useful lexical bindings than the top-level
1431 @code{defcallback} form.
1433 Finally, we make a halfhearted effort to prevent non-local exits from
1434 unwinding the C stack, covering the most likely case with an
1435 @code{error} handler, which is usually triggered
1436 unexpectedly.@footnote{Unfortunately, we can't protect against
1437 @emph{all} non-local exits, such as @code{return}s and @code{throw}s,
1438 because @code{unwind-protect} cannot be used to ``short-circuit'' a
1439 non-local exit in Common Lisp, due to proposal @code{minimal} in
1440 @uref{http://www.lisp.org/HyperSpec/Issues/iss152-writeup.html,
1441 @acronym{ANSI} issue @sc{Exit-Extent}}. Furthermore, binding an
1442 @code{error} handler prevents higher-up code from invoking restarts
1443 that may be provided under the callback's dynamic context. Such is
1444 the way of compromise.} The reason is that most C code is written to
1445 understand its own idiosyncratic error condition, implemented above in
1446 the case of @code{curl_easy_perform}, and more ``undefined behavior''
1447 can result if we just wipe C stack frames without allowing them to
1448 execute whatever cleanup actions as they like.
1450 Using the @code{CURLoption} enumeration in @file{curl.h} once more, we
1451 can describe the new option by modifying and reevaluating
1452 @code{define-curl-options}.
1455 (define-curl-options curl-option
1456 (long 0 objectpoint 10000 functionpoint 20000 off-t 30000)
1457 (:noprogress long 43)
1459 (:errorbuffer objectpoint 10)
1460 (:url objectpoint 2)
1461 (:writefunction functionpoint 11)) ;@lispcmt{new item here}
1464 Finally, we can use the defined callback and the new
1465 @code{set-curl-option-writefunction} to finish configuring the easy
1466 handle, using the @code{callback} macro to retrieve a @cffi{}
1467 @code{:pointer}, which works like a function pointer in C code.
1470 @sc{cffi-user>} (set-curl-option-writefunction
1471 *easy-handle* (callback easy-write))
1476 @node Tutorial-Completion, Tutorial-Types, Tutorial-Callbacks, Tutorial
1477 @section A complete @acronym{FFI}?
1479 @c TeX goes insane on @uref{@clikicffi{}}
1481 With all options finally set and a medium-level interface developed,
1482 we can finish the definition and retrieve
1483 @uref{http://www.cliki.net/CFFI}, as is done in the tutorial.
1486 (defcfun "curl_easy_perform" curl-code
1487 (handle easy-handle))
1491 @sc{cffi-user>} (with-output-to-string (contents)
1492 (let ((*easy-write-procedure*
1494 (write-string string contents))))
1495 (declare (special *easy-write-procedure*))
1496 (curl-easy-perform *easy-handle*)))
1497 @result{} "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"
1499 Now fear, comprehensively</P>
1503 Of course, that itself is slightly unwieldy, so you may want to define
1504 a function around it that simply retrieves a @acronym{URL}. I will
1505 leave synthesis of all the relevant @acronym{REPL} forms presented
1506 thus far into a single function as an exercise for the reader.
1508 The remaining sections of this tutorial explore some advanced features
1509 of @cffi{}; the definition of new types will receive special
1510 attention. Some of these features are essential for particular
1511 foreign function calls; some are very helpful when trying to develop a
1512 Lispy interface to C.
1515 @node Tutorial-Types, Tutorial-Conclusion, Tutorial-Completion, Tutorial
1516 @section Defining new types
1518 We've occasionally used the @code{defctype} macro in previous sections
1519 as a kind of documentation, much what you'd use @code{typedef} for in
1520 C. We also tried one special kind of type definition, the
1521 @code{defcenum} type. @xref{defcstruct}, for a definition macro that
1522 may come in handy if you need to use C @code{struct}s as data.
1524 @cindex type definition
1525 @cindex data in Lisp and C
1526 @cindex translating types
1527 However, all of these are mostly sugar for the powerful underlying
1528 foreign type interface called @dfn{type translators}. You can easily
1529 define new translators for any simple named foreign type. Since we've
1530 defined the new type @code{curl-code} to use as the return type for
1531 various @code{libcurl} functions, we can use that to directly convert
1532 c@acronym{URL} errors to Lisp errors.
1534 @code{defctype}'s purpose is to define simple @code{typedef}-like
1535 aliases. In order to use @dfn{type translators} we must use the
1536 @code{define-foreign-type} macro. So let's redefine @code{curl-code}
1540 (define-foreign-type curl-code-type ()
1543 (:simple-parser curl-code))
1546 @code{define-foreign-type} is a thin wrapper around @code{defclass}.
1547 For now, all you need to know in the context of this example is that
1548 it does what @code{(defctype curl-code :int)} would do and,
1549 additionally, defines a new class @code{curl-code-type} which we will
1550 take advantage of shortly.
1552 The @code{CURLcode} enumeration seems to follow the typical error code
1553 convention of @samp{0} meaning all is well, and each non-zero integer
1554 indicating a different kind of error. We can apply that trivially to
1555 differentiate between normal exits and error exits.
1558 (define-condition curl-code-error (error)
1559 (($code :initarg :curl-code :reader curl-error-code))
1560 (:report (lambda (c stream)
1561 (format stream "libcurl function returned error ~A"
1562 (curl-error-code c))))
1563 (:documentation "Signalled when a libcurl function answers
1564 a code other than CURLE_OK."))
1566 (defmethod translate-from-foreign (value (type curl-code-type))
1567 "Raise a CURL-CODE-ERROR if VALUE, a curl-code, is non-zero."
1570 (error 'curl-code-error :curl-code value)))
1574 The heart of this translator is new method
1575 @code{translate-from-foreign}. By specializing the @var{type}
1576 parameter on @code{curl-code-type}, we immediately modify the behavior
1577 of every function that returns a @code{curl-code} to pass the result
1578 through this new method.
1580 To see the translator in action, try invoking a function that returns
1581 a @code{curl-code}. You need to reevaluate the respective
1582 @code{defcfun} form so that it picks up the new @code{curl-code}
1586 @sc{cffi-user>} (set-curl-option-nosignal *easy-handle* 1)
1591 As the result was @samp{0}, the new method returned @code{:curle-ok},
1592 just as specified.@footnote{It might be better to return
1593 @code{(values)} than @code{:curle-ok} in real code, but this is good
1594 for illustration.} I will leave disjoining the separate
1595 @code{CURLcode}s into condition types and improving the @code{:report}
1596 function as an exercise for you.
1598 The creation of @code{*easy-handle-cstrings*} and
1599 @code{*easy-handle-errorbuffers*} as properties of @code{easy-handle}s
1600 is a kluge. What we really want is a Lisp structure that stores these
1601 properties along with the C pointer. Unfortunately,
1602 @code{easy-handle} is currently just a fancy name for the foreign type
1603 @code{:pointer}; the actual pointer object varies from Common Lisp
1604 implementation to implementation, needing only to satisfy
1605 @code{pointerp} and be returned from @code{make-pointer} and friends.
1607 One solution that would allow us to define a new Lisp structure to
1608 represent @code{easy-handle}s would be to write a wrapper around every
1609 function that currently takes an @code{easy-handle}; the wrapper would
1610 extract the pointer and pass it to the foreign function. However, we
1611 can use type translators to more elegantly integrate this
1612 ``translation'' into the foreign function calling framework, using
1613 @code{translate-to-foreign}.
1616 (defclass easy-handle ()
1617 ((pointer :initform (curl-easy-init)
1618 :documentation "Foreign pointer from curl_easy_init")
1620 :initform (foreign-alloc :char :count *curl-error-size*
1622 :documentation "C string describing last error")
1623 (c-strings :initform '()
1624 :documentation "C strings set as options"))
1625 (:documentation "I am a parameterization you may pass to
1626 curl-easy-perform to perform a cURL network protocol request."))
1628 (defmethod initialize-instance :after ((self easy-handle) &key)
1629 (set-curl-option-errorbuffer self (slot-value self 'error-buffer)))
1631 (defun add-curl-handle-cstring (handle cstring)
1632 "Add CSTRING to be freed when HANDLE is, answering CSTRING."
1633 (car (push cstring (slot-value handle 'c-strings))))
1635 (defun get-easy-handle-error (handle)
1636 "Answer a string containing HANDLE's current error message."
1637 (foreign-string-to-lisp
1638 (slot-value handle 'error-buffer)))
1640 (defun free-easy-handle (handle)
1641 "Free CURL easy interface HANDLE and any C strings created to
1643 (with-slots (pointer error-buffer c-strings) handle
1644 (curl-easy-cleanup pointer)
1645 (foreign-free error-buffer)
1646 (mapc #'foreign-string-free c-strings)))
1648 (define-foreign-type easy-handle-type ()
1650 (:actual-type :pointer)
1651 (:simple-parser easy-handle))
1653 (defmethod translate-to-foreign (handle (type easy-handle-type))
1654 "Extract the pointer from an easy-HANDLE."
1655 (slot-value handle 'pointer))
1658 While we changed some of the Lisp functions defined earlier to use
1659 @acronym{CLOS} slots rather than hash tables, the foreign functions
1660 work just as well as they did before.
1662 @cindex limitations of type translators
1663 The greatest strength, and the greatest limitation, of the type
1664 translator comes from its generalized interface. As stated
1665 previously, we could define all foreign function calls in terms of the
1666 primitive foreign types provided by @cffi{}. The type translator
1667 interface allows us to cleanly specify the relationship between Lisp
1668 and C data, independent of where it appears in a function call. This
1669 independence comes at a price; for example, it cannot be used to
1670 modify translation semantics based on other arguments to a function
1671 call. In these cases, you should rely on other features of Lisp,
1672 rather than the powerful, yet domain-specific, type translator
1676 @node Tutorial-Conclusion, , Tutorial-Types, Tutorial
1677 @section What's next?
1679 @cffi{} provides a rich and powerful foundation for communicating with
1680 foreign libraries; as we have seen, it is up to you to make that
1681 experience a pleasantly Lispy one. This tutorial does not cover all
1682 the features of @cffi{}; please see the rest of the manual for
1683 details. In particular, if something seems obviously missing, it is
1684 likely that either code or a good reason for lack of code is already
1687 @impnote{There are some other things in @cffi{} that might deserve
1688 tutorial sections, such as free-translated-object, or structs. Let us
1689 know which ones you care about.}
1692 @c ===================================================================
1693 @c CHAPTER: Wrapper generators
1695 @node Wrapper generators, Foreign Types, Tutorial, Top
1696 @chapter Wrapper generators
1698 @cffi{}'s interface is designed for human programmers, being aimed at
1699 aesthetic as well as technical sophistication. However, there are a
1700 few programs aimed at translating C and C++ header files, or
1701 approximations thereof, into @cffi{} forms constituting a foreign
1702 interface to the symbols in those files.
1704 These wrapper generators are known to support output of @cffi{} forms.
1707 @item @uref{http://www.cliki.net/Verrazano,Verrazano}
1708 Designed specifically for Common Lisp. Uses @acronym{GCC}'s parser
1709 output in @acronym{XML} format to discover functions, variables, and
1710 other header file data. This means you need @acronym{GCC} to generate
1711 forms; on the other hand, the parser employed is mostly compliant with
1714 @item @uref{http://www.cliki.net/SWIG,SWIG}
1715 A foreign interface generator originally designed to generate Python
1716 bindings, it has been ported to many other systems, including @cffi{}
1717 in version 1.3.28. Includes its own C declaration munger, not
1718 intended to be fully-compliant with @acronym{ANSI} C.
1721 First, this manual does not describe use of these other programs; they
1722 have documentation of their own. If you have problems using a
1723 generated interface, please look at the output @cffi{} forms and
1724 verify that they are a correct @cffi{} interface to the library in
1725 question; if they are correct, contact @cffi{} developers with
1726 details, keeping in mind that they communicate in terms of those forms
1727 rather than any particular wrapper generator. Otherwise, contact the
1728 maintainers of the wrapper generator you are using, provided you can
1729 reasonably expect more accuracy from the generator.
1731 When is more accuracy an unreasonable expectation? As described in
1732 the tutorial (@pxref{Tutorial-Abstraction,, Breaking the
1733 abstraction}), the information in C declarations is insufficient to
1734 completely describe every interface. In fact, it is quite common to
1735 run into an interface that cannot be handled automatically, and
1736 generators should be excused from generating a complete interface in
1739 As further described in the tutorial, the thinnest Lisp interface to a
1740 C function is not always the most pleasant one. In many cases, you
1741 will want to manually write a Lispier interface to the C functions
1744 Wrapper generators should be treated as time-savers, not complete
1745 automation of the full foreign interface writing job. Reports of the
1746 amount of work done by generators vary from 30% to 90%. The
1747 incremental development style enabled by @cffi{} generally reduces
1748 this proportion below that for languages like Python.
1750 @c Where I got the above 30-90% figures:
1751 @c 30%: lemonodor's post about SWIG
1752 @c 90%: Balooga on #lisp. He said 99%, but that's probably an
1753 @c exaggeration (leave it to me to pass judgement :)
1757 @c ===================================================================
1758 @c CHAPTER: Foreign Types
1760 @node Foreign Types, Pointers, Wrapper generators, Top
1761 @chapter Foreign Types
1763 Foreign types describe how data is translated back and forth between C
1764 and Lisp. @cffi{} provides various built-in types and allows the user to
1770 * Defining Foreign Types::
1771 * Foreign Type Translators::
1772 * Optimizing Type Translators::
1773 * Foreign Structure Types::
1774 * Allocating Foreign Objects::
1778 * convert-from-foreign::
1779 * convert-to-foreign::
1785 @c * define-type-spec-parser::
1786 * define-foreign-type::
1787 * define-parse-method::
1788 @c * explain-foreign-slot-value:
1789 * foreign-bitfield-symbols::
1790 * foreign-bitfield-value::
1791 * foreign-enum-keyword::
1792 * foreign-enum-value::
1793 * foreign-slot-names::
1794 * foreign-slot-offset::
1795 * foreign-slot-pointer::
1796 * foreign-slot-value::
1797 * foreign-type-alignment::
1798 * foreign-type-size::
1799 * free-converted-object::
1800 * free-translated-object::
1801 * translate-from-foreign::
1802 * translate-to-foreign::
1803 * translate-into-foreign-memory::
1804 * with-foreign-slots::
1807 @node Built-In Types, Other Types, Foreign Types, Foreign Types
1808 @section Built-In Types
1811 @ForeignType{:unsigned-char}
1812 @ForeignType{:short}
1813 @ForeignType{:unsigned-short}
1815 @ForeignType{:unsigned-int}
1817 @ForeignType{:unsigned-long}
1818 @ForeignType{:long-long}
1819 @ForeignType{:unsigned-long-long}
1821 These types correspond to the native C integer types according to the
1822 @acronym{ABI} of the Lisp implementation's host system.
1824 @code{:long-long} and @code{:unsigned-long-long} are not supported
1825 natively on all implementations. However, they are emulated by
1826 @code{mem-ref} and @code{mem-set}.
1828 When those types are @strong{not} available, the symbol
1829 @code{cffi-sys::no-long-long} is pushed into @code{*features*}.
1831 @ForeignType{:uchar}
1832 @ForeignType{:ushort}
1834 @ForeignType{:ulong}
1835 @ForeignType{:llong}
1836 @ForeignType{:ullong}
1838 For convenience, the above types are provided as shortcuts for
1839 @code{unsigned-char}, @code{unsigned-short}, @code{unsigned-int},
1840 @code{unsigned-long}, @code{long-long} and @code{unsigned-long-long},
1844 @ForeignType{:uint8}
1845 @ForeignType{:int16}
1846 @ForeignType{:uint16}
1847 @ForeignType{:int32}
1848 @ForeignType{:uint32}
1849 @ForeignType{:int64}
1850 @ForeignType{:uint64}
1852 Foreign integer types of specific sizes, corresponding to the C types
1853 defined in @code{stdint.h}.
1855 @c @ForeignType{:size}
1856 @c @ForeignType{:ssize}
1857 @c @ForeignType{:ptrdiff}
1858 @c @ForeignType{:time}
1860 @c Foreign integer types corresponding to the standard C types (without
1861 @c the @code{_t} suffix).
1863 @c @impnote{These are not implemented yet. --luis}
1865 @c @impnote{I'm sure there are more of these that could be useful, let's
1866 @c add any types that can't be defined portably to this list as
1867 @c necessary. --james}
1869 @ForeignType{:float}
1870 @ForeignType{:double}
1872 On all systems, the @code{:float} and @code{:double} types represent a
1873 C @code{float} and @code{double}, respectively. On most but not all
1874 systems, @code{:float} and @code{:double} represent a Lisp
1875 @code{single-float} and @code{double-float}, respectively. It is not
1876 so useful to consider the relationship between Lisp types and C types
1877 as isomorphic, as simply to recognize the relationship, and relative
1878 precision, among each respective category.
1880 @ForeignType{:long-double}
1882 This type is only supported on SCL.
1884 @ForeignType{:pointer &optional type}
1886 A foreign pointer to an object of any type, corresponding to
1887 @code{void *}. You can optionally specify type of pointer
1888 (e.g. @code{(:pointer :char)}). Although @cffi{} won't do anything
1889 with that information yet, it is useful for documentation purposes.
1893 No type at all. Only valid as the return type of a function.
1895 @node Other Types, Defining Foreign Types, Built-In Types, Foreign Types
1896 @section Other Types
1898 @cffi{} also provides a few useful types that aren't built-in C
1901 @ForeignType{:string}
1903 The @code{:string} type performs automatic conversion between Lisp and
1904 C strings. Note that, in the case of functions the converted C string
1905 will have dynamic extent (i.e.@: it will be automatically freed after
1906 the foreign function returns).
1908 In addition to Lisp strings, this type will accept foreign pointers
1909 and pass them unmodified.
1911 A method for @ref{free-translated-object} is specialized for this
1912 type. So, for example, foreign strings allocated by this type and
1913 passed to a foreign function will be freed after the function
1917 CFFI> (foreign-funcall "getenv" :string "SHELL" :string)
1918 @result{} "/bin/bash"
1920 CFFI> (with-foreign-string (str "abcdef")
1921 (foreign-funcall "strlen" :string str :int))
1925 @ForeignType{:string+ptr}
1927 Like @code{:string} but returns a list with two values when convert
1928 from C to Lisp: a Lisp string and the C string's foreign pointer.
1931 CFFI> (foreign-funcall "getenv" :string "SHELL" :string+ptr)
1932 @result{} ("/bin/bash" #.(SB-SYS:INT-SAP #XBFFFFC6F))
1935 @ForeignType{:boolean &optional (base-type :int)}
1937 The @code{:boolean} type converts between a Lisp boolean and a C
1938 boolean. It canonicalizes to @var{base-type} which is @code{:int} by
1942 (convert-to-foreign nil :boolean) @result{} 0
1943 (convert-to-foreign t :boolean) @result{} 1
1944 (convert-from-foreign 0 :boolean) @result{} nil
1945 (convert-from-foreign 1 :boolean) @result{} t
1950 The @code{:bool} type represents the C99 @code{_Bool} or C++
1951 @code{bool}. Its size is usually 1 byte except on OSX where it's an
1954 @ForeignType{:wrapper base-type &key to-c from-c}
1956 The @code{:wrapper} type stores two symbols passed to the @var{to-c}
1957 and @var{from-c} arguments. When a value is being translated to or
1958 from C, this type @code{funcall}s the respective symbol.
1960 @code{:wrapper} types will be typedefs for @var{base-type} and will
1961 inherit its translators, if any.
1963 Here's an example of how the @code{:boolean} type could be defined in
1964 terms of @code{:wrapper}.
1967 (defun bool-c-to-lisp (value)
1968 (not (zerop value)))
1970 (defun bool-lisp-to-c (value)
1973 (defctype my-bool (:wrapper :int :from-c bool-c-to-lisp
1974 :to-c bool-lisp-to-c))
1976 (convert-to-foreign nil 'my-bool) @result{} 0
1977 (convert-from-foreign 1 'my-bool) @result{} t
1980 @node Defining Foreign Types, Foreign Type Translators, Other Types, Foreign Types
1981 @section Defining Foreign Types
1983 You can define simple C-like @code{typedef}s through the
1984 @code{defctype} macro. Defining a typedef is as simple as giving
1985 @code{defctype} a new name and the name of the type to be wrapped.
1988 ;;; @lispcmt{Define MY-INT as an alias for the built-in type :INT.}
1989 (defctype my-int :int)
1992 With this type definition, one can, for instance, declare arguments to
1993 foreign functions as having the type @code{my-int}, and they will be
1996 @subheading More complex types
1998 @cffi{} offers another way to define types through
1999 @code{define-foreign-type}, a thin wrapper macro around
2000 @code{defclass}. As an example, let's go through the steps needed to
2001 define a @code{(my-string &key encoding)} type. First, we need to
2002 define our type class:
2005 (define-foreign-type my-string-type ()
2006 ((encoding :reader string-type-encoding :initarg :encoding))
2007 (:actual-type :pointer))
2010 The @code{:actual-type} class option tells CFFI that this type will
2011 ultimately be passed to and received from foreign code as a
2012 @code{:pointer}. Now you need to tell CFFI how to parse a type
2013 specification such as @code{(my-string :encoding :utf8)} into an
2014 instance of @code{my-string-type}. We do that with
2015 @code{define-parse-method}:
2018 (define-parse-method my-string (&key (encoding :utf-8))
2019 (make-instance 'my-string-type :encoding encoding))
2022 The next section describes how make this type actually translate
2023 between C and Lisp strings.
2025 @node Foreign Type Translators, Optimizing Type Translators, Defining Foreign Types, Foreign Types
2026 @section Foreign Type Translators
2028 Type translators are used to automatically convert Lisp values to or
2029 from foreign values. For example, using type translators, one can
2030 take the @code{my-string} type defined in the previous section and
2031 specify that it should:
2035 convert C strings to Lisp strings;
2037 convert Lisp strings to newly allocated C strings;
2039 free said C strings when they are no longer needed.
2042 In order to tell @cffi{} how to automatically convert Lisp values to
2043 foreign values, define a specialized method for the
2044 @code{translate-to-foreign} generic function:
2047 ;;; @lispcmt{Define a method that converts Lisp strings to C strings.}
2048 (defmethod translate-to-foreign (string (type my-string-type))
2049 (foreign-string-alloc string :encoding (string-type-encoding type)))
2053 From now on, whenever an object is passed as a @code{my-string} to a
2054 foreign function, this method will be invoked to convert the Lisp
2055 value. To perform the inverse operation, which is needed for functions
2056 that return a @code{my-string}, specialize the
2057 @code{translate-from-foreign} generic function in the same manner:
2060 ;;; @lispcmt{Define a method that converts C strings to Lisp strings.}
2061 (defmethod translate-from-foreign (pointer (type my-string-type))
2062 (foreign-string-to-lisp pointer :encoding (string-type-encoding type)))
2066 When a @code{translate-to-foreign} method requires allocation of
2067 foreign memory, you must also define a @code{free-translated-object}
2068 method to free the memory once the foreign object is no longer needed,
2069 otherwise you'll be faced with memory leaks. This generic function is
2070 called automatically by @cffi{} when passing objects to foreign
2071 functions. Let's do that:
2074 ;;; @lispcmt{Free strings allocated by translate-to-foreign.}
2075 (defmethod free-translated-object (pointer (type my-string-type) param)
2076 (declare (ignore param))
2077 (foreign-string-free pointer))
2081 In this specific example, we don't need the @var{param} argument, so
2082 we ignore it. See @ref{free-translated-object}, for an explanation of
2083 its purpose and how you can use it.
2085 A type translator does not necessarily need to convert the value. For
2086 example, one could define a typedef for @code{:pointer} that ensures,
2087 in the @code{translate-to-foreign} method, that the value is not a
2088 null pointer, signalling an error if a null pointer is passed. This
2089 would prevent some pointer errors when calling foreign functions that
2090 cannot handle null pointers.
2092 @strong{Please note:} these methods are meant as extensible hooks
2093 only, and you should not call them directly. Use
2094 @code{convert-to-foreign}, @code{convert-from-foreign} and
2095 @code{free-converted-object} instead.
2097 @xref{Tutorial-Types,, Defining new types}, for another example of
2100 @node Optimizing Type Translators, Foreign Structure Types, Foreign Type Translators, Foreign Types
2101 @section Optimizing Type Translators
2103 @cindex type translators, optimizing
2104 @cindex compiler macros for type translation
2105 @cindex defining type-translation compiler macros
2106 Being based on generic functions, the type translation mechanism
2107 described above can add a bit of overhead. This is usually not
2108 significant, but we nevertheless provide a way of getting rid of the
2109 overhead for the cases where it matters.
2111 A good way to understand this issue is to look at the code generated
2112 by @code{defcfun}. Consider the following example using the previously
2113 defined @code{my-string} type:
2116 CFFI> (macroexpand-1 '(defcfun foo my-string (x my-string)))
2117 ;; @lispcmt{(simplified, downcased, etc...)}
2119 (multiple-value-bind (#:G2019 #:PARAM3149)
2120 (translate-to-foreign x #<MY-STRING-TYPE @{11ED5A79@}>)
2122 (translate-from-foreign
2123 (foreign-funcall "foo" :pointer #:G2019 :pointer)
2124 #<MY-STRING-TYPE @{11ED5659@}>)
2125 (free-translated-object #:G2019 #<MY-STRING-TYPE @{11ED51A79@}>
2130 In order to get rid of those generic function calls, @cffi{} has
2131 another set of extensible generic functions that provide functionality
2132 similar to @acronym{CL}'s compiler macros:
2133 @code{expand-to-foreign-dyn}, @code{expand-to-foreign} and
2134 @code{expand-from-foreign}. Here's how one could define a
2135 @code{my-boolean} with them:
2138 (define-foreign-type my-boolean-type ()
2141 (:simple-parser my-boolean))
2143 (defmethod expand-to-foreign (value (type my-boolean-type))
2146 (defmethod expand-from-foreign (value (type my-boolean-type))
2147 `(not (zerop ,value)))
2151 And here's what the macroexpansion of a function using this type would
2155 CFFI> (macroexpand-1 '(defcfun bar my-boolean (x my-boolean)))
2156 ;; @lispcmt{(simplified, downcased, etc...)}
2158 (let ((#:g3182 (if x 1 0)))
2159 (not (zerop (foreign-funcall "bar" :int #:g3182 :int)))))
2163 No generic function overhead.
2165 Let's go back to our @code{my-string} type. The expansion interface
2166 has no equivalent of @code{free-translated-object}; you must instead
2167 define a method on @code{expand-to-foreign-dyn}, the third generic
2168 function in this interface. This is especially useful when you can
2169 allocate something much more efficiently if you know the object has
2170 dynamic extent, as is the case with function calls that don't save the
2171 relevant allocated arguments.
2173 This exactly what we need for the @code{my-string} type:
2176 (defmethod expand-from-foreign (form (type my-string-type))
2177 `(foreign-string-to-lisp ,form))
2179 (defmethod expand-to-foreign-dyn (value var body (type my-string-type))
2180 (let ((encoding (string-type-encoding type)))
2181 `(with-foreign-string (,var ,value :encoding ',encoding)
2186 So let's look at the macro expansion:
2189 CFFI> (macroexpand-1 '(defcfun foo my-string (x my-string)))
2190 ;; @lispcmt{(simplified, downcased, etc...)}
2192 (with-foreign-string (#:G2021 X :encoding ':utf-8)
2193 (foreign-string-to-lisp
2194 (foreign-funcall "foo" :pointer #:g2021 :pointer))))
2198 Again, no generic function overhead.
2200 @subheading Other details
2202 To short-circuit expansion and use the @code{translate-*} functions
2203 instead, simply call the next method. Return its result in cases
2204 where your method cannot generate an appropriate replacement for it.
2205 This analogous to the @code{&whole form} mechanism compiler macros
2208 The @code{expand-*} methods have precedence over their
2209 @code{translate-*} counterparts and are guaranteed to be used in
2210 @code{defcfun}, @code{foreign-funcall}, @code{defcvar} and
2211 @code{defcallback}. If you define a method on each of the
2212 @code{expand-*} generic functions, you are guaranteed to have full
2213 control over the expressions generated for type translation in these
2216 They may or may not be used in other @cffi{} operators that need to
2217 translate between Lisp and C data; you may only assume that
2218 @code{expand-*} methods will probably only be called during Lisp
2221 @code{expand-to-foreign-dyn} has precedence over
2222 @code{expand-to-foreign} and is only used in @code{defcfun} and
2223 @code{foreign-funcall}, only making sense in those contexts.
2225 @strong{Important note:} this set of generic functions is called at
2226 macroexpansion time. Methods are defined when loaded or evaluated,
2227 not compiled. You are responsible for ensuring that your
2228 @code{expand-*} methods are defined when the @code{foreign-funcall} or
2229 other forms that use them are compiled. One way to do this is to put
2230 the method definitions earlier in the file and inside an appropriate
2231 @code{eval-when} form; another way is to always load a separate Lisp
2232 or @acronym{FASL} file containing your @code{expand-*} definitions
2233 before compiling files with forms that ought to use them. Otherwise,
2234 they will not be found and the runtime translators will be used
2237 @node Foreign Structure Types, Allocating Foreign Objects, Optimizing Type Translators, Foreign Types
2238 @section Foreign Structure Types
2240 For more involved C types than simple aliases to built-in types, such
2241 as you can make with @code{defctype}, @cffi{} allows declaration of
2242 structures and unions with @code{defcstruct} and @code{defcunion}.
2244 For example, consider this fictional C structure declaration holding
2245 some personal information:
2255 The equivalent @code{defcstruct} form follows:
2263 @c LMH structure translation
2264 By default, @ref{convert-from-foreign} (and also @ref{mem-ref}) will
2265 make a plist with slot names as keys, and @ref{convert-to-foreign} will
2266 translate such a plist to a foreign structure. A user wishing to define
2267 other translations should use the @code{:class} argument to
2268 @ref{defcstruct}, and then define methods for
2269 @ref{translate-from-foreign} and
2270 @ref{translate-into-foreign-memory} that specialize on this class,
2271 possibly calling @code{call-next-method} to translate from and to the
2272 plists rather than provide a direct interface to the foreign object.
2273 The macro @code{translation-forms-for-class} will generate the forms
2274 necessary to translate a Lisp class into a foreign structure and vice
2276 @c Write separate function doc section for translation-forms-for-class?
2277 @c Examples, perhaps taken from the tests?
2279 Please note that this interface is only for those that must know about
2280 the values contained in a relevant struct. If the library you are
2281 interfacing returns an opaque pointer that needs only be passed to
2282 other C library functions, by all means just use @code{:pointer} or a
2283 type-safe definition munged together with @code{defctype} and type
2284 translation. To pass or return a structure by value to a function, load
2285 the cffi-libffi system and specify the structure as @code{(:struct
2286 @var{structure-name})}. To pass or return the pointer, you can use
2287 either @code{:pointer} or @code{(:pointer (:struct
2288 @var{structure-name}))}.
2290 @subheading Optimizing translate-into-foreign-memory
2292 Just like how @ref{translate-from-foreign} had
2293 @code{expand-from-foreign} to optimize away the generic function call
2294 and @ref{translate-to-foreign} had the same in
2295 @code{expand-to-foreign}, @ref{translate-into-foreign-memory} has
2296 @code{expand-into-foreign-memory}.
2298 Let's use our @code{person} struct in an example. However, we are
2299 going to spice it up by using a lisp struct rather than a plist to
2300 represent the person in lisp.
2302 First we redefine @code{person} very slightly.
2305 (defcstruct (person :class c-person)
2310 By adding @code{:class} we can specialize the @code{translate-*}
2311 methods on the type @code{c-person}.
2313 Next we define a lisp struct to use instead of the plists.
2316 (defstruct lisp-person
2317 (number 0 :type integer)
2318 (reason "" :type string))
2321 And now let's define the type translators we know already:
2324 (defmethod translate-from-foreign (ptr (type c-person))
2325 (with-foreign-slots ((number reason) ptr (:struct person))
2326 (make-lisp-person :number number :reason reason)))
2328 (defmethod expand-from-foreign (ptr (type c-person))
2329 `(with-foreign-slots ((number reason) ,ptr (:struct person))
2330 (make-lisp-person :number number :reason reason)))
2332 (defmethod translate-into-foreign-memory (value (type c-person) ptr)
2333 (with-foreign-slots ((number reason) ptr (:struct person))
2334 (setf number (lisp-person-number value)
2335 reason (lisp-person-reason value))))
2338 At this point everything works, we can convert to and from our
2339 @code{lisp-person} and foreign @code{person}. If we macroexpand
2342 (setf (mem-aref ptr '(:struct person)) x)
2345 we get something like:
2348 (let ((#:store879 x))
2349 (translate-into-foreign-memory #:store879 #<c-person person>
2350 (inc-pointer ptr 0))
2354 Which is good, but now we can do better and get rid of that generic
2355 function call to @code{translate-into-foreign-memory}.
2358 (defmethod expand-into-foreign-memory (value (type c-person) ptr)
2359 `(with-foreign-slots ((number reason) ,ptr (:struct person))
2360 (setf number (lisp-person-number ,value)
2361 reason (lisp-person-reason ,value))))
2364 Now we can expand again so see the changes:
2368 (setf (mem-aref ptr '(:struct person)) x)
2371 ;; (simplified, downcased, etc..)
2372 (let ((#:store887 x))
2373 (with-foreign-slots ((number reason) (inc-pointer ptr 0) (:struct person))
2374 (setf number (lisp-person-number #:store887)
2375 reason (lisp-person-reason #:store887))) #:store887)
2378 And there we are, no generic function overhead.
2380 @subheading Compatibility note
2382 Previous versions of CFFI accepted the
2383 ``bare'' @var{structure-name} as a type specification, which was
2384 interpreted as a pointer to the structure. This is deprecated and
2385 produces a style warning. Using this deprecated form means that
2386 @ref{mem-aref} retains its prior meaning and returns a pointer. Using
2387 the @code{(:struct @var{structure-name})} form for the type,
2388 @ref{mem-aref} provides a Lisp object translated from the
2389 structure (by default a plist). Thus the semantics are consistent with all
2390 types in returning the object as represented in Lisp, and not a pointer,
2391 with the exception of the ``bare'' structure compatibility retained.
2392 In order to obtain the pointer, you should use the function @ref{mem-aptr}.
2394 See @ref{defcstruct} for more details.
2396 @node Allocating Foreign Objects, convert-from-foreign, Foreign Structure Types, Foreign Types
2397 @section Allocating Foreign Objects
2399 @c I moved this because I moved with-foreign-object to the Pointers
2400 @c chapter, where foreign-alloc is.
2402 @xref{Allocating Foreign Memory}.
2405 @c ===================================================================
2406 @c CONVERT-FROM-FOREIGN
2409 @node convert-from-foreign, convert-to-foreign, Allocating Foreign Objects, Foreign Types
2410 @heading convert-from-foreign
2412 @Function{convert-from-foreign foreign-value type @res{} value}
2414 @subheading Arguments and Values
2418 The primitive C value as returned from a primitive foreign function or
2419 from @code{convert-to-foreign}.
2422 A @cffi{} type specifier.
2425 The Lisp value translated from @var{foreign-value}.
2428 @subheading Description
2430 This is an external interface to the type translation facility. In
2431 the implementation, all foreign functions are ultimately defined as
2432 type translation wrappers around primitive foreign function
2435 This function is available mostly for inspection of the type
2436 translation process, and possibly optimization of special cases of
2437 your foreign function calls.
2439 Its behavior is better described under @code{translate-from-foreign}'s
2442 @subheading Examples
2445 CFFI-USER> (convert-to-foreign "a boat" :string)
2446 @result{} #<FOREIGN-ADDRESS #x097ACDC0>
2448 CFFI-USER> (convert-from-foreign * :string)
2452 @subheading See Also
2453 @seealso{convert-to-foreign} @*
2454 @seealso{free-converted-object} @*
2455 @seealso{translate-from-foreign}
2458 @c ===================================================================
2459 @c CONVERT-TO-FOREIGN
2462 @node convert-to-foreign, defbitfield, convert-from-foreign, Foreign Types
2463 @heading convert-to-foreign
2465 @Function{convert-to-foreign value type @res{} foreign-value, alloc-params}
2467 @subheading Arguments and Values
2471 The Lisp object to be translated to a foreign object.
2474 A @cffi{} type specifier.
2477 The primitive C value, ready to be passed to a primitive foreign
2481 Something of a translation state; you must pass it to
2482 @code{free-converted-object} along with the foreign value for that to
2486 @subheading Description
2488 This is an external interface to the type translation facility. In
2489 the implementation, all foreign functions are ultimately defined as
2490 type translation wrappers around primitive foreign function
2493 This function is available mostly for inspection of the type
2494 translation process, and possibly optimization of special cases of
2495 your foreign function calls.
2497 Its behavior is better described under @code{translate-to-foreign}'s
2500 @subheading Examples
2503 CFFI-USER> (convert-to-foreign t :boolean)
2506 CFFI-USER> (convert-to-foreign "hello, world" :string)
2507 @result{} #<FOREIGN-ADDRESS #x097C5F80>
2509 CFFI-USER> (code-char (mem-aref * :char 5))
2513 @subheading See Also
2514 @seealso{convert-from-foreign} @*
2515 @seealso{free-converted-object} @*
2516 @seealso{translate-to-foreign}
2519 @c ===================================================================
2523 @node defbitfield, defcstruct, convert-to-foreign, Foreign Types
2524 @heading defbitfield
2526 @Macro{defbitfield name-and-options &body masks}
2528 masks ::= [docstring] @{ (symbol value) @}* @*
2529 name-and-options ::= name | (name &optional (base-type :int))
2531 @subheading Arguments and Values
2535 The name of the new bitfield type.
2538 A documentation string, ignored.
2541 A symbol denoting a foreign type.
2547 An integer representing a bitmask.
2550 @subheading Description
2551 The @code{defbitfield} macro is used to define foreign types that map
2552 lists of symbols to integer values.
2554 If @var{value} is omitted, it will be computed as follows: find the
2555 greatest @var{value} previously used, including those so computed,
2556 with only a single 1-bit in its binary representation (that is, powers
2557 of two), and left-shift it by one. This rule guarantees that a
2558 computed @var{value} cannot clash with previous values, but may clash
2559 with future explicitly specified values.
2561 Symbol lists will be automatically converted to values and vice versa
2562 when being passed as arguments to or returned from foreign functions,
2563 respectively. The same applies to any other situations where an object
2564 of a bitfield type is expected.
2566 Types defined with @code{defbitfield} canonicalize to @var{base-type}
2567 which is @code{:int} by default.
2569 @subheading Examples
2571 (defbitfield open-flags
2573 :wronly ;@lispcmt{#x0001}
2574 :rdwr ;@lispcmt{@dots{}}
2578 ;; @lispcmt{etc@dots{}}
2580 CFFI> (foreign-bitfield-symbols 'open-flags #b1101)
2581 @result{} (:WRONLY :NONBLOCK :APPEND)
2583 CFFI> (foreign-bitfield-value 'open-flags '(:rdwr :creat))
2584 @result{} 514 ; #x0202
2586 (defcfun ("open" unix-open) :int
2589 (mode :uint16)) ; unportable
2591 CFFI> (unix-open "/tmp/foo" '(:wronly :creat) #o644)
2594 ;;; @lispcmt{Consider also the following lispier wrapper around open()}
2595 (defun lispier-open (path mode &rest flags)
2596 (unix-open path flags mode))
2599 @subheading See Also
2600 @seealso{foreign-bitfield-value} @*
2601 @seealso{foreign-bitfield-symbols}
2604 @c ===================================================================
2608 @node defcstruct, defcunion, defbitfield, Foreign Types
2611 @Macro{defcstruct name-and-options &body doc-and-slots @res{} name}
2613 name-and-options ::= structure-name | (structure-name &key size)
2615 doc-and-slots ::= [docstring] @{ (slot-name slot-type &key count offset) @}*
2617 @subheading Arguments and Values
2620 @item structure-name
2621 The name of new structure type.
2624 A documentation string, ignored.
2627 A symbol naming the slot. It must be unique among slot names in this
2631 Use this option to override the size (in bytes) of the struct.
2634 The type specifier for the slot.
2637 Used to declare an array of size @var{count} inside the
2638 structure. Defaults to @code{1} as such an array and a single element
2639 are semantically equivalent.
2642 Overrides the slot's offset. The next slot's offset is calculated
2646 @subheading Description
2647 This defines a new @cffi{} aggregate type akin to C @code{struct}s.
2648 In other words, it specifies that foreign objects of the type
2649 @var{structure-name} are groups of different pieces of data, or
2650 ``slots'', of the @var{slot-type}s, distinguished from each other by
2651 the @var{slot-name}s. Each structure is located in memory at a
2652 position, and the slots are allocated sequentially beginning at that
2653 point in memory (with some padding allowances as defined by the C
2654 @acronym{ABI}, unless otherwise requested by specifying an
2655 @var{offset} from the beginning of the structure (offset 0).
2657 In other words, it is isomorphic to the C @code{struct}, giving
2658 several extra features.
2660 There are two kinds of slots, for the two kinds of @cffi{} types:
2664 Contain a single instance of a type that canonicalizes to a built-in
2665 type, such as @code{:long} or @code{:pointer}. Used for simple
2669 Contain an embedded structure or union, or an array of objects. Used
2670 for aggregate @cffi{} types.
2673 The use of @acronym{CLOS} terminology for the structure-related
2674 features is intentional; structure definitions are very much like
2675 classes with (far) fewer features.
2677 @subheading Examples
2684 CFFI> (with-foreign-object (ptr 'point)
2685 ;; @lispcmt{Initialize the slots}
2686 (setf (foreign-slot-value ptr 'point 'x) 42
2687 (foreign-slot-value ptr 'point 'y) 42)
2688 ;; @lispcmt{Return a list with the coordinates}
2689 (with-foreign-slots ((x y) ptr point)
2695 ;; @lispcmt{Using the :size and :offset options to define a partial structure.}
2696 ;; @lispcmt{(this is useful when you are interested in only a few slots}
2697 ;; @lispcmt{of a big foreign structure)}
2699 (defcstruct (foo :size 32)
2700 "Some struct with 32 bytes."
2701 ; @lispcmt{<16 bytes we don't care about>}
2702 (x :int :offset 16) ; @lispcmt{an int at offset 16}
2703 (y :int) ; @lispcmt{another int at offset 16+sizeof(int)}
2704 ; @lispcmt{<a couple more bytes we don't care about>}
2705 (z :char :offset 24)) ; @lispcmt{a char at offset 24}
2706 ; @lispcmt{<7 more bytes ignored (since size is 32)>}
2708 CFFI> (foreign-type-size 'foo)
2713 ;;; @lispcmt{Using :count to define arrays inside of a struct.}
2714 (defcstruct video_tuner
2715 (name :char :count 32))
2718 @subheading See Also
2719 @seealso{foreign-slot-pointer} @*
2720 @seealso{foreign-slot-value} @*
2721 @seealso{with-foreign-slots}
2724 @c ===================================================================
2728 @node defcunion, defctype, defcstruct, Foreign Types
2731 @Macro{defcunion name &body doc-and-slots @res{} name}
2733 doc-and-slots ::= [docstring] @{ (slot-name slot-type &key count) @}*
2735 @subheading Arguments and Values
2739 The name of new union type.
2742 A documentation string, ignored.
2745 A symbol naming the slot.
2748 The type specifier for the slot.
2751 Used to declare an array of size @var{count} inside the
2755 @subheading Description
2756 A union is a structure in which all slots have an offset of zero. It
2757 is isomorphic to the C @code{union}. Therefore, you should use the
2758 usual foreign structure operations for accessing a union's slots.
2760 @subheading Examples
2762 (defcunion uint32-bytes
2763 (int-value :unsigned-int)
2764 (bytes :unsigned-char :count 4))
2767 @subheading See Also
2768 @seealso{foreign-slot-pointer} @*
2769 @seealso{foreign-slot-value}
2772 @c ===================================================================
2776 @node defctype, defcenum, defcunion, Foreign Types
2779 @Macro{defctype name base-type &optional documentation}
2781 @subheading Arguments and Values
2785 The name of the new foreign type.
2788 A symbol or a list defining the new type.
2791 A documentation string, currently ignored.
2794 @subheading Description
2795 The @code{defctype} macro provides a mechanism similar to C's
2796 @code{typedef} to define new types. The new type inherits
2797 @var{base-type}'s translators, if any. There is no way to define
2798 translations for types defined with @code{defctype}. For that,
2799 you should use @ref{define-foreign-type}.
2801 @subheading Examples
2803 (defctype my-string :string
2804 "My own string type.")
2806 (defctype long-bools (:boolean :long)
2807 "Booleans that map to C longs.")
2810 @subheading See Also
2811 @seealso{define-foreign-type}
2814 @c ===================================================================
2818 @node defcenum, define-foreign-type, defctype, Foreign Types
2821 @Macro{defcenum name-and-options &body enum-list}
2823 enum-list ::= [docstring] @{ keyword | (keyword value) @}*
2824 name-and-options ::= name | (name &optional (base-type :int))
2826 @subheading Arguments and Values
2830 The name of the new enum type.
2833 A documentation string, ignored.
2836 A symbol denoting a foreign type.
2842 An index value for a keyword.
2845 @subheading Description
2846 The @code{defcenum} macro is used to define foreign types that map
2847 keyword symbols to integer values, similar to the C @code{enum} type.
2849 If @var{value} is omitted its value will either be 0, if it's the
2850 first entry, or it it will continue the progression from the last
2853 Keywords will be automatically converted to values and vice-versa when
2854 being passed as arguments to or returned from foreign functions,
2855 respectively. The same applies to any other situations where an object
2856 of an @code{enum} type is expected.
2858 Types defined with @code{defcenum} canonicalize to @var{base-type}
2859 which is @code{:int} by default.
2861 @subheading Examples
2867 CFFI> (foreign-enum-value 'boolean :no)
2877 CFFI> (foreign-enum-keyword 'numbers 2)
2881 @subheading See Also
2882 @seealso{foreign-enum-value} @*
2883 @seealso{foreign-enum-keyword}
2886 @c ===================================================================
2887 @c DEFINE-FOREIGN-TYPE
2890 @node define-foreign-type, define-parse-method, defcenum, Foreign Types
2891 @heading define-foreign-type
2893 @Macro{define-foreign-type class-name supers slots &rest options @res{} class-name}
2895 options ::= (@code{:actual-type} @var{type}) | @
2896 (@code{:simple-parser} @var{symbol}) | @
2897 @emph{regular defclass option}
2899 @subheading Arguments and Values
2903 A symbol naming the new foreign type class.
2906 A list of symbols naming the super classes.
2909 A list of slot definitions, passed to @code{defclass}.
2912 @subheading Description
2916 The macro @code{define-foreign-type} defines a new class
2917 @var{class-name}. It is a thin wrapper around @code{defclass}. Among
2918 other things, it ensures that @var{class-name} becomes a subclass of
2919 @var{foreign-type}, what you need to know about that is that there's
2920 an initarg @code{:actual-type} which serves the same purpose as
2921 @code{defctype}'s @var{base-type} argument.
2923 @c TODO mention the type translators here
2926 @subheading Examples
2927 Taken from @cffi{}'s @code{:boolean} type definition:
2930 (define-foreign-type :boolean (&optional (base-type :int))
2931 "Boolean type. Maps to an :int by default. Only accepts integer types."
2938 :unsigned-long) base-type)))
2940 CFFI> (canonicalize-foreign-type :boolean)
2942 CFFI> (canonicalize-foreign-type '(:boolean :long))
2944 CFFI> (canonicalize-foreign-type '(:boolean :float))
2945 ;; @lispcmt{@error{} signalled by ECASE.}
2948 @subheading See Also
2949 @seealso{defctype} @*
2950 @seealso{define-parse-method}
2953 @c ===================================================================
2954 @c DEFINE-PARSE-METHOD
2957 @node define-parse-method, foreign-bitfield-symbols, define-foreign-type, Foreign Types
2958 @heading define-parse-method
2960 @Macro{define-parse-method name lambda-list &body body @res{} name}
2962 @subheading Arguments and Values
2966 A symbol naming the new foreign type.
2969 A lambda list which is the argument list of the new foreign type.
2972 One or more forms that provide a definition of the new foreign type.
2975 @subheading Description
2978 @c TODO: update example. The boolean type is probably a good choice.
2980 @subheading Examples
2981 Taken from @cffi{}'s @code{:boolean} type definition:
2984 (define-foreign-type :boolean (&optional (base-type :int))
2985 "Boolean type. Maps to an :int by default. Only accepts integer types."
2992 :unsigned-long) base-type)))
2994 CFFI> (canonicalize-foreign-type :boolean)
2996 CFFI> (canonicalize-foreign-type '(:boolean :long))
2998 CFFI> (canonicalize-foreign-type '(:boolean :float))
2999 ;; @lispcmt{@error{} signalled by ECASE.}
3002 @subheading See Also
3003 @seealso{define-foreign-type}
3006 @c ===================================================================
3007 @c EXPLAIN-FOREIGN-SLOT-VALUE
3009 @c @node explain-foreign-slot-value
3010 @c @heading explain-foreign-slot-value
3011 @c @subheading Syntax
3012 @c @Macro{explain-foreign-slot-value ptr type &rest slot-names}
3014 @c @subheading Arguments and Values
3027 @c @subheading Description
3028 @c This macro translates the slot access that would occur by calling
3029 @c @code{foreign-slot-value} with the same arguments into an equivalent
3030 @c expression in C and prints it to @code{*standard-output*}.
3032 @c @emph{Note: this is not implemented yet.}
3034 @c @subheading Examples
3036 @c CFFI> (explain-foreign-slot-value ptr 'timeval 'tv-secs)
3037 @c @result{} ptr->tv_secs
3039 @c CFFI> (explain-foreign-slot-value emp 'employee 'hire-date 'tv-usecs)
3040 @c @result{} emp->hire_date.tv_usecs
3043 @c @subheading See Also
3046 @c ===================================================================
3047 @c FOREIGN-BITFIELD-SYMBOLS
3050 @node foreign-bitfield-symbols, foreign-bitfield-value, define-parse-method, Foreign Types
3051 @heading foreign-bitfield-symbols
3053 @Function{foreign-bitfield-symbols type value @res{} symbols}
3055 @subheading Arguments and Values
3065 A potentially shared list of symbols.
3069 @subheading Description
3070 The function @code{foreign-bitfield-symbols} returns a possibly shared
3071 list of symbols that correspond to @var{value} in @var{type}.
3073 @subheading Examples
3080 CFFI> (foreign-bitfield-symbols 'flags #b101)
3081 @result{} (FLAG-A FLAG-C)
3084 @subheading See Also
3085 @seealso{defbitfield} @*
3086 @seealso{foreign-bitfield-value}
3089 @c ===================================================================
3090 @c FOREIGN-BITFIELD-VALUE
3093 @node foreign-bitfield-value, foreign-enum-keyword, foreign-bitfield-symbols, Foreign Types
3094 @heading foreign-bitfield-value
3096 @Function{foreign-bitfield-value type symbols @res{} value}
3098 @subheading Arguments and Values
3102 A @code{bitfield} type.
3111 @subheading Description
3112 The function @code{foreign-bitfield-value} returns the @var{value} that
3113 corresponds to the symbols in the @var{symbols} list.
3115 @subheading Examples
3122 CFFI> (foreign-bitfield-value 'flags '(flag-a flag-c))
3126 @subheading See Also
3127 @seealso{defbitfield} @*
3128 @seealso{foreign-bitfield-symbols}
3131 @c ===================================================================
3132 @c FOREIGN-ENUM-KEYWORD
3135 @node foreign-enum-keyword, foreign-enum-value, foreign-bitfield-value, Foreign Types
3136 @heading foreign-enum-keyword
3138 @Function{foreign-enum-keyword type value &key errorp @res{} keyword}
3140 @subheading Arguments and Values
3144 An @code{enum} type.
3150 If true (the default), signal an error if @var{value} is not defined
3151 in @var{type}. If false, @code{foreign-enum-keyword} returns
3158 @subheading Description
3159 The function @code{foreign-enum-keyword} returns the keyword symbol
3160 that corresponds to @var{value} in @var{type}.
3162 An error is signaled if @var{type} doesn't contain such @var{value}
3163 and @var{errorp} is true.
3165 @subheading Examples
3171 CFFI> (foreign-enum-keyword 'boolean 1)
3175 @subheading See Also
3176 @seealso{defcenum} @*
3177 @seealso{foreign-enum-value}
3180 @c ===================================================================
3181 @c FOREIGN-ENUM-VALUE
3184 @node foreign-enum-value, foreign-slot-names, foreign-enum-keyword, Foreign Types
3185 @heading foreign-enum-value
3187 @Function{foreign-enum-value type keyword &key errorp @res{} value}
3189 @subheading Arguments and Values
3193 An @code{enum} type.
3199 If true (the default), signal an error if @var{keyword} is not
3200 defined in @var{type}. If false, @code{foreign-enum-value} returns
3207 @subheading Description
3208 The function @code{foreign-enum-value} returns the @var{value} that
3209 corresponds to @var{keyword} in @var{type}.
3211 An error is signaled if @var{type} doesn't contain such
3212 @var{keyword}, and @var{errorp} is true.
3214 @subheading Examples
3220 CFFI> (foreign-enum-value 'boolean :yes)
3224 @subheading See Also
3225 @seealso{defcenum} @*
3226 @seealso{foreign-enum-keyword}
3229 @c ===================================================================
3230 @c FOREIGN-SLOT-NAMES
3233 @node foreign-slot-names, foreign-slot-offset, foreign-enum-value, Foreign Types
3234 @heading foreign-slot-names
3236 @Function{foreign-slot-names type @res{} names}
3238 @subheading Arguments and Values
3242 A foreign struct type.
3248 @subheading Description
3249 The function @code{foreign-slot-names} returns a potentially shared
3250 list of slot @var{names} for the given structure @var{type}. This list
3251 has no particular order.
3253 @subheading Examples
3259 CFFI> (foreign-slot-names '(:struct timeval))
3260 @result{} (TV-SECS TV-USECS)
3263 @subheading See Also
3264 @seealso{defcstruct} @*
3265 @seealso{foreign-slot-offset} @*
3266 @seealso{foreign-slot-value} @*
3267 @seealso{foreign-slot-pointer}
3270 @c ===================================================================
3271 @c FOREIGN-SLOT-OFFSET
3274 @node foreign-slot-offset, foreign-slot-pointer, foreign-slot-names, Foreign Types
3275 @heading foreign-slot-offset
3277 @Function{foreign-slot-offset type slot-name @res{} offset}
3279 @subheading Arguments and Values
3283 A foreign struct type.
3292 @subheading Description
3293 The function @code{foreign-slot-offset} returns the @var{offset} in
3294 bytes of a slot in a foreign struct type.
3296 @subheading Examples
3302 CFFI> (foreign-slot-offset '(:struct timeval) 'tv-secs)
3304 CFFI> (foreign-slot-offset '(:struct timeval) 'tv-usecs)
3308 @subheading See Also
3309 @seealso{defcstruct} @*
3310 @seealso{foreign-slot-names} @*
3311 @seealso{foreign-slot-pointer} @*
3312 @seealso{foreign-slot-value}
3315 @c ===================================================================
3316 @c FOREIGN-SLOT-POINTER
3319 @node foreign-slot-pointer, foreign-slot-value, foreign-slot-offset, Foreign Types
3320 @heading foreign-slot-pointer
3322 @Function{foreign-slot-pointer ptr type slot-name @res{} pointer}
3324 @subheading Arguments and Values
3328 A pointer to a structure.
3331 A foreign structure type.
3334 A slot name in the @var{type}.
3337 A pointer to the slot @var{slot-name}.
3340 @subheading Description
3341 Returns a pointer to the location of the slot @var{slot-name} in a
3342 foreign object of type @var{type} at @var{ptr}. The returned pointer
3343 points inside the structure. Both the pointer and the memory it points
3344 to have the same extent as @var{ptr}.
3346 For aggregate slots, this is the same value returned by
3347 @code{foreign-slot-value}.
3349 @subheading Examples
3352 "Pointer structure."
3356 CFFI> (with-foreign-object (ptr '(:struct point))
3357 (foreign-slot-pointer ptr '(:struct point) 'x))
3358 @result{} #<FOREIGN-ADDRESS #xBFFF6E60>
3359 ;; @lispcmt{Note: the exact pointer representation varies from lisp to lisp.}
3362 @subheading See Also
3363 @seealso{defcstruct} @*
3364 @seealso{foreign-slot-value} @*
3365 @seealso{foreign-slot-names} @*
3366 @seealso{foreign-slot-offset}
3369 @c ===================================================================
3370 @c FOREIGN-SLOT-VALUE
3373 @node foreign-slot-value, foreign-type-alignment, foreign-slot-pointer, Foreign Types
3374 @heading foreign-slot-value
3376 @Accessor{foreign-slot-value ptr type slot-name @res{} object}
3378 @subheading Arguments and Values
3382 A pointer to a structure.
3385 A foreign structure type.
3388 A symbol naming a slot in the structure type.
3391 The object contained in the slot specified by @var{slot-name}.
3394 @subheading Description
3395 For simple slots, @code{foreign-slot-value} returns the value of the
3396 object, such as a Lisp integer or pointer. In C, this would be
3397 expressed as @code{ptr->slot}.
3399 For aggregate slots, a pointer inside the structure to the beginning
3400 of the slot's data is returned. In C, this would be expressed as
3401 @code{&ptr->slot}. This pointer and the memory it points to have the
3402 same extent as @var{ptr}.
3404 There are compiler macros for @code{foreign-slot-value} and its
3405 @code{setf} expansion that open code the memory access when
3406 @var{type} and @var{slot-names} are constant at compile-time.
3408 @subheading Examples
3411 "Pointer structure."
3415 CFFI> (with-foreign-object (ptr '(:struct point))
3416 ;; @lispcmt{Initialize the slots}
3417 (setf (foreign-slot-value ptr '(:struct point) 'x) 42
3418 (foreign-slot-value ptr '(:struct point) 'y) 42)
3419 ;; @lispcmt{Return a list with the coordinates}
3420 (with-foreign-slots ((x y) ptr (:struct point))
3425 @subheading See Also
3426 @seealso{defcstruct} @*
3427 @seealso{foreign-slot-names} @*
3428 @seealso{foreign-slot-offset} @*
3429 @seealso{foreign-slot-pointer} @*
3430 @seealso{with-foreign-slots}
3433 @c ===================================================================
3434 @c FOREIGN-TYPE-ALIGNMENT
3437 @node foreign-type-alignment, foreign-type-size, foreign-slot-value, Foreign Types
3438 @heading foreign-type-alignment
3440 @c XXX: This is actually a generic function.
3441 @Function{foreign-type-alignment type @res{} alignment}
3443 @subheading Arguments and Values
3453 @subheading Description
3454 The function @code{foreign-type-alignment} returns the
3455 @var{alignment} of @var{type} in bytes.
3457 @subheading Examples
3459 CFFI> (foreign-type-alignment :char)
3461 CFFI> (foreign-type-alignment :short)
3463 CFFI> (foreign-type-alignment :int)
3471 CFFI> (foreign-type-alignment '(:struct foo))
3475 @subheading See Also
3476 @seealso{foreign-type-size}
3479 @c ===================================================================
3480 @c FOREIGN-TYPE-SIZE
3483 @node foreign-type-size, free-converted-object, foreign-type-alignment, Foreign Types
3484 @heading foreign-type-size
3486 @c XXX: this is actually a generic function.
3487 @Function{foreign-type-size type @res{} size}
3489 @subheading Arguments and Values
3499 @subheading Description
3500 The function @code{foreign-type-size} return the @var{size} of
3501 @var{type} in bytes. This includes any padding within and following
3502 the in-memory representation as needed to create an array of
3505 @subheading Examples
3511 CFFI> (foreign-type-size :double)
3513 CFFI> (foreign-type-size :char)
3515 CFFI> (foreign-type-size '(:struct foo))
3519 @subheading See Also
3520 @seealso{foreign-type-alignment}
3523 @c ===================================================================
3524 @c FREE-CONVERTED-OBJECT
3527 @node free-converted-object, free-translated-object, foreign-type-size, Foreign Types
3528 @heading free-converted-object
3530 @Function{free-converted-object foreign-value type params}
3532 @subheading Arguments and Values
3536 The C object to be freed.
3539 A @cffi{} type specifier.
3542 The state returned as the second value from @code{convert-to-foreign};
3543 used to implement the third argument to @code{free-translated-object}.
3546 @subheading Description
3548 The return value is unspecified.
3550 This is an external interface to the type translation facility. In
3551 the implementation, all foreign functions are ultimately defined as
3552 type translation wrappers around primitive foreign function
3555 This function is available mostly for inspection of the type
3556 translation process, and possibly optimization of special cases of
3557 your foreign function calls.
3559 Its behavior is better described under @code{free-translated-object}'s
3562 @subheading Examples
3565 CFFI-USER> (convert-to-foreign "a boat" :string)
3566 @result{} #<FOREIGN-ADDRESS #x097ACDC0>
3568 CFFI-USER> (free-converted-object * :string t)
3572 @subheading See Also
3573 @seealso{convert-from-foreign} @*
3574 @seealso{convert-to-foreign} @*
3575 @seealso{free-translated-object}
3578 @c ===================================================================
3579 @c FREE-TRANSLATED-OBJECT
3584 @node free-translated-object, translate-from-foreign, free-converted-object, Foreign Types
3585 @heading free-translated-object
3587 @GenericFunction{free-translated-object value type-name param}
3589 @subheading Arguments and Values
3593 The foreign value returned by @code{translate-to-foreign}.
3596 A symbol naming a foreign type defined by @code{defctype}.
3599 The second value, if any, returned by @code{translate-to-foreign}.
3602 @subheading Description
3603 This generic function may be specialized by user code to perform
3604 automatic deallocation of foreign objects as they are passed to C
3607 Any methods defined on this generic function must EQL-specialize the
3608 @var{type-name} parameter on a symbol defined as a foreign type by
3609 the @code{defctype} macro.
3611 @subheading See Also
3612 @seealso{Foreign Type Translators} @*
3613 @seealso{translate-to-foreign}
3616 @c ===================================================================
3617 @c TRANSLATE-FROM-FOREIGN
3622 @node translate-from-foreign, translate-to-foreign, free-translated-object, Foreign Types
3623 @heading translate-from-foreign
3625 @GenericFunction{translate-from-foreign foreign-value type-name @
3628 @subheading Arguments and Values
3632 The foreign value to convert to a Lisp object.
3635 A symbol naming a foreign type defined by @code{defctype}.
3638 The lisp value to pass in place of @code{foreign-value} to Lisp code.
3641 @subheading Description
3642 This generic function is invoked by @cffi{} to convert a foreign value to
3643 a Lisp value, such as when returning from a foreign function, passing
3644 arguments to a callback function, or accessing a foreign variable.
3646 To extend the @cffi{} type system by performing custom translations, this
3647 method may be specialized by @sc{eql}-specializing @code{type-name} on a
3648 symbol naming a foreign type defined with @code{defctype}. This
3649 method should return the appropriate Lisp value to use in place of the
3652 The results are undefined if the @code{type-name} parameter is
3653 specialized in any way except an @sc{eql} specializer on a foreign type
3654 defined with @code{defctype}. Specifically, translations may not be
3655 defined for built-in types.
3657 @subheading See Also
3658 @seealso{Foreign Type Translators} @*
3659 @seealso{translate-to-foreign} @*
3660 @seealso{free-translated-object}
3663 @c ===================================================================
3664 @c TRANSLATE-TO-FOREIGN
3669 @node translate-to-foreign, translate-into-foreign-memory, translate-from-foreign, Foreign Types
3670 @heading translate-to-foreign
3672 @GenericFunction{translate-to-foreign lisp-value type-name @
3673 @res{} foreign-value, alloc-param}
3675 @subheading Arguments and Values
3679 The Lisp value to convert to foreign representation.
3682 A symbol naming a foreign type defined by @code{defctype}.
3685 The foreign value to pass in place of @code{lisp-value} to foreign code.
3688 If present, this value will be passed to
3689 @code{free-translated-object}.
3692 @subheading Description
3693 This generic function is invoked by @cffi{} to convert a Lisp value to a
3694 foreign value, such as when passing arguments to a foreign function,
3695 returning a value from a callback, or setting a foreign variable. A
3696 ``foreign value'' is one appropriate for passing to the next-lowest
3697 translator, including the low-level translators that are ultimately
3698 invoked invisibly with @cffi{}.
3700 To extend the @cffi{} type system by performing custom translations, this
3701 method may be specialized by @sc{eql}-specializing @code{type-name} on a
3702 symbol naming a foreign type defined with @code{defctype}. This
3703 method should return the appropriate foreign value to use in place of
3706 In cases where @cffi{} can determine the lifetime of the foreign object
3707 returned by this method, it will invoke @code{free-translated-object}
3708 on the foreign object at the appropriate time. If
3709 @code{translate-to-foreign} returns a second value, it will be passed
3710 as the @code{param} argument to @code{free-translated-object}. This
3711 can be used to establish communication between the allocation and
3712 deallocation methods.
3714 The results are undefined if the @code{type-name} parameter is
3715 specialized in any way except an @sc{eql} specializer on a foreign type
3716 defined with @code{defctype}. Specifically, translations may not be
3717 defined for built-in types.
3719 @subheading See Also
3720 @seealso{Foreign Type Translators} @*
3721 @seealso{translate-from-foreign} @*
3722 @seealso{free-translated-object}
3725 @c ===================================================================
3726 @c TRANSLATE-INTO-FOREIGN-MEMORY
3729 @node translate-into-foreign-memory, with-foreign-slots, translate-to-foreign, Foreign Types
3730 @heading translate-into-foreign-memory
3732 @GenericFunction{translate-into-foreign-memory lisp-value type-name pointer}
3734 @subheading Arguments and Values
3738 The Lisp value to convert to foreign representation.
3741 A symbol or list @code{(:struct @var{structure-name})} naming a foreign type defined by @code{defctype}.
3744 The foreign pointer where the translated object should be stored.
3747 @subheading Description
3748 Translate the Lisp value into the foreign memory location given by
3749 pointer. The return value is not used.
3751 @c ===================================================================
3752 @c WITH-FOREIGN-SLOTS
3755 @node with-foreign-slots, , translate-into-foreign-memory, Foreign Types
3756 @heading with-foreign-slots
3758 @Macro{with-foreign-slots (vars ptr type) &body body}
3760 @subheading Arguments and Values
3764 A list with each element a symbol, or list of length two with the
3765 first element @code{:pointer} and the second a symbol.
3768 A foreign pointer to a structure.
3774 A list of forms to be executed.
3777 @subheading Description
3778 The @code{with-foreign-slots} macro creates local symbol macros for each
3779 var in @var{vars} to reference foreign slots in @var{ptr} of @var{type}.
3780 If the var is a list starting with @code{:pointer}, it will bind the
3781 pointer to the slot (rather than the value). It is similar to Common
3782 Lisp's @code{with-slots} macro.
3784 @subheading Examples
3799 CFFI> (with-foreign-object (time :int)
3800 (setf (mem-ref time :int)
3801 (foreign-funcall "time" :pointer (null-pointer) :int))
3802 (foreign-funcall "gmtime" :pointer time (:pointer (:struct tm))))
3803 @result{} #<A Mac Pointer #x102A30>
3804 CFFI> (with-foreign-slots ((sec min hour mday mon year) * (:struct tm))
3805 (format nil "~A:~A:~A, ~A/~A/~A"
3806 hour min sec (+ 1900 year) mon mday))
3807 @result{} "7:22:47, 2005/8/2"
3810 @subheading See Also
3811 @seealso{defcstruct} @*
3812 @seealso{defcunion} @*
3813 @seealso{foreign-slot-value}
3816 @c ===================================================================
3817 @c CHAPTER: Pointers
3819 @node Pointers, Strings, Foreign Types, Top
3822 All C data in @cffi{} is referenced through pointers. This includes
3823 defined C variables that hold immediate values, and integers.
3825 To see why this is, consider the case of the C integer. It is not
3826 only an arbitrary representation for an integer, congruent to Lisp's
3827 fixnums; the C integer has a specific bit pattern in memory defined by
3828 the C @acronym{ABI}. Lisp has no such constraint on its fixnums;
3829 therefore, it only makes sense to think of fixnums as C integers if
3830 you assume that @cffi{} converts them when necessary, such as when
3831 storing one for use in a C function call, or as the value of a C
3832 variable. This requires defining an area of memory@footnote{The
3833 definition of @dfn{memory} includes the @acronym{CPU} registers.},
3834 represented through an effective address, and storing it there.
3836 Due to this compartmentalization, it only makes sense to manipulate
3837 raw C data in Lisp through pointers to it. For example, while there
3838 may be a Lisp representation of a @code{struct} that is converted to C
3839 at store time, you may only manipulate its raw data through a pointer.
3840 The C compiler does this also, albeit informally.
3843 * Basic Pointer Operations::
3844 * Allocating Foreign Memory::
3845 * Accessing Foreign Memory::
3851 * foreign-symbol-pointer::
3863 * with-foreign-object::
3864 * with-foreign-objects::
3865 * with-foreign-pointer::
3868 @node Basic Pointer Operations, Allocating Foreign Memory, Pointers, Pointers
3869 @section Basic Pointer Operations
3871 Manipulating pointers proper can be accomplished through most of the
3872 other operations defined in the Pointers dictionary, such as
3873 @code{make-pointer}, @code{pointer-address}, and @code{pointer-eq}.
3874 When using them, keep in mind that they merely manipulate the Lisp
3875 representation of pointers, not the values they point to.
3877 @deftp {Lisp Type} foreign-pointer
3878 The pointers' representations differ from implementation to
3879 implementation and have different types. @code{foreign-pointer}
3880 provides a portable type alias to each of these types.
3884 @node Allocating Foreign Memory, Accessing Foreign Memory, Basic Pointer Operations, Pointers
3885 @section Allocating Foreign Memory
3887 @cffi{} provides support for stack and heap C memory allocation.
3888 Stack allocation, done with @code{with-foreign-object}, is sometimes
3889 called ``dynamic'' allocation in Lisp, because memory allocated as
3890 such has dynamic extent, much as with @code{let} bindings of special
3893 This should not be confused with what C calls ``dynamic'' allocation,
3894 or that done with @code{malloc} and friends. This sort of heap
3895 allocation is done with @code{foreign-alloc}, creating objects that
3896 exist until freed with @code{foreign-free}.
3899 @node Accessing Foreign Memory, foreign-free, Allocating Foreign Memory, Pointers
3900 @section Accessing Foreign Memory
3902 When manipulating raw C data, consider that all pointers are pointing
3903 to an array. When you only want one C value, such as a single
3904 @code{struct}, this array only has one such value. It is worthwhile
3905 to remember that everything is an array, though, because this is also
3906 the semantic that C imposes natively.
3908 C values are accessed as the @code{setf}-able places defined by
3909 @code{mem-aref} and @code{mem-ref}. Given a pointer and a @cffi{}
3910 type (@pxref{Foreign Types}), either of these will dereference the
3911 pointer, translate the C data there back to Lisp, and return the
3912 result of said translation, performing the reverse operation when
3913 @code{setf}-ing. To decide which one to use, consider whether you
3914 would use the array index operator @code{[@var{n}]} or the pointer
3915 dereference @code{*} in C; use @code{mem-aref} for array indexing and
3916 @code{mem-ref} for pointer dereferencing.
3919 @c ===================================================================
3923 @node foreign-free, foreign-alloc, Accessing Foreign Memory, Pointers
3924 @heading foreign-free
3926 @Function{foreign-free ptr @res{} undefined}
3928 @subheading Arguments and Values
3935 @subheading Description
3936 The @code{foreign-free} function frees a @code{ptr} previously
3937 allocated by @code{foreign-alloc}. The consequences of freeing a given
3938 pointer twice are undefined.
3940 @subheading Examples
3943 CFFI> (foreign-alloc :int)
3944 @result{} #<A Mac Pointer #x1022E0>
3945 CFFI> (foreign-free *)
3949 @subheading See Also
3950 @seealso{foreign-alloc} @*
3951 @seealso{with-foreign-pointer}
3954 @c ===================================================================
3958 @node foreign-alloc, foreign-symbol-pointer, foreign-free, Pointers
3959 @heading foreign-alloc
3961 @Function{foreign-alloc type &key initial-element initial-contents (count 1) @
3962 null-terminated-p @res{} pointer}
3964 @subheading Arguments and Values
3970 @item initial-element
3973 @item initial-contents
3977 An integer. Defaults to 1 or the length of @var{initial-contents} if
3980 @item null-terminated-p
3981 A boolean, false by default.
3984 A foreign pointer to the newly allocated memory.
3987 @subheading Description
3988 The @code{foreign-alloc} function allocates enough memory to hold
3989 @var{count} objects of type @var{type} and returns a
3990 @var{pointer}. This memory must be explicitly freed using
3991 @code{foreign-free} once it is no longer needed.
3993 If @var{initial-element} is supplied, it is used to initialize the
3994 @var{count} objects the newly allocated memory holds.
3996 If an @var{initial-contents} sequence is supplied, it must have a
3997 length less than or equal to @var{count} and each of its elements
3998 will be used to initialize the contents of the newly allocated
4001 If @var{count} is omitted and @var{initial-contents} is specified, it
4002 will default to @code{(length @var{initial-contents})}.
4004 @var{initial-element} and @var{initial-contents} are mutually
4007 When @var{null-terminated-p} is true,
4008 @code{(1+ (max @var{count} (length @var{initial-contents})))} elements
4009 are allocated and the last one is set to @code{NULL}. Note that in
4010 this case @var{type} must be a pointer type (ie. a type that
4011 canonicalizes to @code{:pointer}), otherwise an error is signaled.
4013 @subheading Examples
4015 CFFI> (foreign-alloc :char)
4016 @result{} #<A Mac Pointer #x102D80> ; @lispcmt{A pointer to 1 byte of memory.}
4018 CFFI> (foreign-alloc :char :count 20)
4019 @result{} #<A Mac Pointer #x1024A0> ; @lispcmt{A pointer to 20 bytes of memory.}
4021 CFFI> (foreign-alloc :int :initial-element 12)
4022 @result{} #<A Mac Pointer #x1028B0>
4023 CFFI> (mem-ref * :int)
4026 CFFI> (foreign-alloc :int :initial-contents '(1 2 3))
4027 @result{} #<A Mac Pointer #x102950>
4028 CFFI> (loop for i from 0 below 3
4029 collect (mem-aref * :int i))
4032 CFFI> (foreign-alloc :int :initial-contents #(1 2 3))
4033 @result{} #<A Mac Pointer #x102960>
4034 CFFI> (loop for i from 0 below 3
4035 collect (mem-aref * :int i))
4038 ;;; @lispcmt{Allocate a char** pointer that points to newly allocated memory}
4039 ;;; @lispcmt{by the :string type translator for the string "foo".}
4040 CFFI> (foreign-alloc :string :initial-element "foo")
4041 @result{} #<A Mac Pointer #x102C40>
4045 ;;; @lispcmt{Allocate a null-terminated array of strings.}
4046 ;;; @lispcmt{(Note: FOREIGN-STRING-TO-LISP returns NIL when passed a null pointer)}
4047 CFFI> (foreign-alloc :string
4048 :initial-contents '("foo" "bar" "baz")
4049 :null-terminated-p t)
4050 @result{} #<A Mac Pointer #x102D20>
4051 CFFI> (loop for i from 0 below 4
4052 collect (mem-aref * :string i))
4053 @result{} ("foo" "bar" "baz" NIL)
4056 (foreign-free (mem-aref ** :pointer i)))
4061 @subheading See Also
4062 @seealso{foreign-free} @*
4063 @seealso{with-foreign-object} @*
4064 @seealso{with-foreign-pointer}
4067 @c ===================================================================
4068 @c FOREIGN-SYMBOL-POINTER
4071 @node foreign-symbol-pointer, inc-pointer, foreign-alloc, Pointers
4072 @heading foreign-symbol-pointer
4074 @Function{foreign-symbol-pointer foreign-name &key library @res{} pointer}
4076 @subheading Arguments and Values
4083 A foreign pointer, or @code{nil}.
4086 A Lisp symbol or an instance of @code{foreign-library}.
4089 @subheading Description
4090 The function @code{foreign-symbol-pointer} will return a foreign
4091 pointer corresponding to the foreign symbol denoted by the string
4092 @var{foreign-name}. If a foreign symbol named @var{foreign-name}
4093 doesn't exist, @code{nil} is returned.
4095 ABI name manglings will be performed on @var{foreign-name} by
4096 @code{foreign-symbol-pointer} if necessary. (eg: adding a leading
4097 underscore on darwin/ppc)
4099 @var{library} should name a foreign library as defined by
4100 @code{define-foreign-library}, @code{:default} (which is the default)
4101 or an instance of @code{foreign-library} as returned by
4102 @code{load-foreign-library}.
4104 @strong{Important note:} do not keep these pointers across saved Lisp
4105 cores as the foreign-library may move across sessions.
4107 @subheading Examples
4110 CFFI> (foreign-symbol-pointer "errno")
4111 @result{} #<A Mac Pointer #xA0008130>
4112 CFFI> (foreign-symbol-pointer "strerror")
4113 @result{} #<A Mac Pointer #x9002D0F8>
4114 CFFI> (foreign-funcall-pointer * () :int (mem-ref ** :int) :string)
4115 @result{} "No such file or directory"
4117 CFFI> (foreign-symbol-pointer "inexistent symbol")
4121 @subheading See Also
4125 @c ===================================================================
4129 @node inc-pointer, incf-pointer, foreign-symbol-pointer, Pointers
4130 @heading inc-pointer
4132 @Function{inc-pointer pointer offset @res{} new-pointer}
4134 @subheading Arguments and Values
4145 @subheading Description
4146 The function @code{inc-pointer} will return a @var{new-pointer} pointing
4147 @var{offset} bytes past @var{pointer}.
4149 @subheading Examples
4152 CFFI> (foreign-string-alloc "Common Lisp")
4153 @result{} #<A Mac Pointer #x102EA0>
4154 CFFI> (inc-pointer * 7)
4155 @result{} #<A Mac Pointer #x102EA7>
4156 CFFI> (foreign-string-to-lisp *)
4160 @subheading See Also
4161 @seealso{incf-pointer} @*
4162 @seealso{make-pointer} @*
4163 @seealso{pointerp} @*
4164 @seealso{null-pointer} @*
4165 @seealso{null-pointer-p}
4168 @c ===================================================================
4172 @node incf-pointer, make-pointer, inc-pointer, Pointers
4173 @heading incf-pointer
4175 @Macro{incf-pointer place &optional (offset 1) @res{} new-pointer}
4177 @subheading Arguments and Values
4181 A @code{setf} place.
4190 @subheading Description
4191 The @code{incf-pointer} macro takes the foreign pointer from
4192 @var{place} and creates a @var{new-pointer} incremented by
4193 @var{offset} bytes and which is stored in @var{place}.
4195 @subheading Examples
4198 CFFI> (defparameter *two-words* (foreign-string-alloc "Common Lisp"))
4199 @result{} *TWO-WORDS*
4200 CFFI> (defparameter *one-word* *two-words*)
4201 @result{} *ONE-WORD*
4202 CFFI> (incf-pointer *one-word* 7)
4203 @result{} #.(SB-SYS:INT-SAP #X00600457)
4204 CFFI> (foreign-string-to-lisp *one-word*)
4206 CFFI> (foreign-string-to-lisp *two-words*)
4207 @result{} "Common Lisp"
4210 @subheading See Also
4211 @seealso{inc-pointer} @*
4212 @seealso{make-pointer} @*
4213 @seealso{pointerp} @*
4214 @seealso{null-pointer} @*
4215 @seealso{null-pointer-p}
4218 @c ===================================================================
4222 @node make-pointer, mem-aptr, incf-pointer, Pointers
4223 @heading make-pointer
4225 @Function{make-pointer address @res{} ptr}
4227 @subheading Arguments and Values
4237 @subheading Description
4238 The function @code{make-pointer} will return a foreign pointer
4239 pointing to @var{address}.
4241 @subheading Examples
4244 CFFI> (make-pointer 42)
4245 @result{} #<FOREIGN-ADDRESS #x0000002A>
4248 CFFI> (pointer-address **)
4250 CFFI> (inc-pointer *** -42)
4251 @result{} #<FOREIGN-ADDRESS #x00000000>
4252 CFFI> (null-pointer-p *)
4254 CFFI> (typep ** 'foreign-pointer)
4258 @subheading See Also
4259 @seealso{inc-pointer} @*
4260 @seealso{null-pointer} @*
4261 @seealso{null-pointer-p} @*
4262 @seealso{pointerp} @*
4263 @seealso{pointer-address} @*
4264 @seealso{pointer-eq} @*
4268 @c ===================================================================
4272 @node mem-aptr, mem-aref, make-pointer, Pointers
4275 @Accessor{mem-aptr ptr type &optional (index 0)}
4277 @subheading Arguments and Values
4290 A Lisp value compatible with @var{type}.
4293 @subheading Description
4294 The @code{mem-aptr} function finds the pointer to an element of the array.
4297 (mem-aptr ptr type n)
4299 ;; @lispcmt{is identical to:}
4301 (inc-pointer ptr (* n (foreign-type-size type)))
4304 @subheading Examples
4307 CFFI> (with-foreign-string (str "Hello, foreign world!")
4308 (mem-aptr str :char 6))
4309 @result{} #.(SB-SYS:INT-SAP #X0063D4B6)
4312 @c ===================================================================
4316 @node mem-aref, mem-ref, mem-aptr, Pointers
4319 @Accessor{mem-aref ptr type &optional (index 0)}
4321 (setf (@strong{mem-aref} @emph{ptr type &optional (index 0)) new-value})
4323 @subheading Arguments and Values
4336 A Lisp value compatible with @var{type}.
4339 @subheading Description
4340 The @code{mem-aref} function is similar to @code{mem-ref} but will
4341 automatically calculate the offset from an @var{index}.
4344 (mem-aref ptr type n)
4346 ;; @lispcmt{is identical to:}
4348 (mem-ref ptr type (* n (foreign-type-size type)))
4351 @subheading Examples
4354 CFFI> (with-foreign-string (str "Hello, foreign world!")
4355 (mem-aref str :char 6))
4360 CFFI> (with-foreign-object (array :int 10)
4361 (loop for i below 10
4362 do (setf (mem-aref array :int i) (random 100)))
4363 (loop for i below 10 collect (mem-aref array :int i)))
4364 @result{} (22 7 22 52 69 1 46 93 90 65)
4367 @subheading Compatibility Note
4369 For compatibility with older versions of CFFI, @ref{mem-aref} will
4370 produce a pointer for the deprecated bare structure specification, but
4371 it is consistent with other types for the current specification form
4372 @code{(:struct @var{structure-name})} and provides a Lisp object
4373 translated from the structure (by default a plist). In order to obtain
4374 the pointer, you should use the new function @ref{mem-aptr}.
4376 @subheading See Also
4377 @seealso{mem-ref} @*
4380 @c ===================================================================
4384 @node mem-ref, null-pointer, mem-aref, Pointers
4387 @Accessor{mem-ref ptr type &optional offset @res{} object}
4389 @subheading Arguments and Values
4399 An integer (in byte units).
4402 The value @var{ptr} points to.
4405 @subheading Description
4406 @subheading Examples
4409 CFFI> (with-foreign-string (ptr "Saluton")
4410 (setf (mem-ref ptr :char 3) (char-code #\a))
4411 (loop for i from 0 below 8
4412 collect (code-char (mem-ref ptr :char i))))
4413 @result{} (#\S #\a #\l #\a #\t #\o #\n #\Null)
4414 CFFI> (setq ptr-to-int (foreign-alloc :int))
4415 @result{} #<A Mac Pointer #x1047D0>
4416 CFFI> (mem-ref ptr-to-int :int)
4418 CFFI> (setf (mem-ref ptr-to-int :int) 1984)
4420 CFFI> (mem-ref ptr-to-int :int)
4424 @subheading See Also
4428 @c ===================================================================
4432 @node null-pointer, null-pointer-p, mem-ref, Pointers
4433 @heading null-pointer
4435 @Function{null-pointer @res{} pointer}
4437 @subheading Arguments and Values
4441 A @code{NULL} pointer.
4444 @subheading Description
4445 The function @code{null-pointer} returns a null pointer.
4447 @subheading Examples
4450 CFFI> (null-pointer)
4451 @result{} #<A Null Mac Pointer>
4456 @subheading See Also
4457 @seealso{null-pointer-p} @*
4458 @seealso{make-pointer}
4461 @c ===================================================================
4465 @node null-pointer-p, pointerp, null-pointer, Pointers
4466 @heading null-pointer-p
4468 @Function{null-pointer-p ptr @res{} boolean}
4470 @subheading Arguments and Values
4474 A foreign pointer that may be a null pointer.
4477 @code{T} or @code{NIL}.
4480 @subheading Description
4481 The function @code{null-pointer-p} returns true if @var{ptr} is a null
4482 pointer and false otherwise.
4484 @subheading Examples
4487 CFFI> (null-pointer-p (null-pointer))
4492 (defun contains-str-p (big little)
4493 (not (null-pointer-p
4494 (foreign-funcall "strstr" :string big :string little :pointer))))
4496 CFFI> (contains-str-p "Popcorns" "corn")
4498 CFFI> (contains-str-p "Popcorns" "salt")
4502 @subheading See Also
4503 @seealso{null-pointer} @*
4507 @c ===================================================================
4511 @node pointerp, pointer-address, null-pointer-p, Pointers
4514 @Function{pointerp ptr @res{} boolean}
4516 @subheading Arguments and Values
4520 An object that may be a foreign pointer.
4523 @code{T} or @code{NIL}.
4526 @subheading Description
4527 The function @code{pointerp} returns true if @var{ptr} is a foreign
4528 pointer and false otherwise.
4530 @subheading Implementation-specific Notes
4531 In Allegro CL, foreign pointers are integers thus in this
4532 implementation @code{pointerp} will return true for any ordinary integer.
4534 @subheading Examples
4537 CFFI> (foreign-alloc 32)
4538 @result{} #<A Mac Pointer #x102D20>
4541 CFFI> (pointerp "this is not a pointer")
4545 @subheading See Also
4546 @seealso{make-pointer}
4547 @seealso{null-pointer-p}
4550 @c ===================================================================
4554 @node pointer-address, pointer-eq, pointerp, Pointers
4555 @heading pointer-address
4557 @Function{pointer-address ptr @res{} address}
4559 @subheading Arguments and Values
4569 @subheading Description
4570 The function @code{pointer-address} will return the @var{address} of
4571 a foreign pointer @var{ptr}.
4573 @subheading Examples
4576 CFFI> (pointer-address (null-pointer))
4578 CFFI> (pointer-address (make-pointer 123))
4582 @subheading See Also
4583 @seealso{make-pointer} @*
4584 @seealso{inc-pointer} @*
4585 @seealso{null-pointer} @*
4586 @seealso{null-pointer-p} @*
4587 @seealso{pointerp} @*
4588 @seealso{pointer-eq} @*
4592 @c ===================================================================
4596 @node pointer-eq, with-foreign-object, pointer-address, Pointers
4599 @Function{pointer-eq ptr1 ptr2 @res{} boolean}
4601 @subheading Arguments and Values
4609 @code{T} or @code{NIL}.
4612 @subheading Description
4613 The function @code{pointer-eq} returns true if @var{ptr1} and
4614 @var{ptr2} point to the same memory address and false otherwise.
4616 @subheading Implementation-specific Notes
4617 The representation of foreign pointers varies across the various Lisp
4618 implementations as does the behaviour of the built-in Common Lisp
4619 equality predicates. Comparing two pointers that point to the same
4620 address with @code{EQ} Lisps will return true on some Lisps, others require
4621 more general predicates like @code{EQL} or @code{EQUALP} and finally
4622 some will return false using any of these predicates. Therefore, for
4623 portability, you should use @code{POINTER-EQ}.
4625 @subheading Examples
4626 This is an example using @acronym{SBCL}, see the
4627 implementation-specific notes above.
4630 CFFI> (eql (null-pointer) (null-pointer))
4632 CFFI> (pointer-eq (null-pointer) (null-pointer))
4636 @subheading See Also
4637 @seealso{inc-pointer}
4640 @c ===================================================================
4641 @c WITH-FOREIGN-OBJECT
4644 @node with-foreign-object, with-foreign-pointer, pointer-eq, Pointers
4645 @heading with-foreign-object, with-foreign-objects
4647 @Macro{with-foreign-object (var type &optional count) &body body}
4649 @anchor{with-foreign-objects}
4650 @Macro{with-foreign-objects (bindings) &body body}
4652 bindings ::= @{(var type &optional count)@}*
4654 @subheading Arguments and Values
4661 A foreign type, evaluated.
4667 @subheading Description
4668 The macros @code{with-foreign-object} and @code{with-foreign-objects}
4669 bind @var{var} to a pointer to @var{count} newly allocated objects
4670 of type @var{type} during @var{body}. The buffer has dynamic extent
4671 and may be stack allocated if supported by the host Lisp.
4673 @subheading Examples
4676 CFFI> (with-foreign-object (array :int 10)
4678 (setf (mem-aref array :int i) (random 100)))
4679 (loop for i below 10
4680 collect (mem-aref array :int i)))
4681 @result{} (22 7 22 52 69 1 46 93 90 65)
4684 @subheading See Also
4685 @seealso{foreign-alloc}
4688 @c ===================================================================
4689 @c WITH-FOREIGN-POINTER
4692 @node with-foreign-pointer, , with-foreign-object, Pointers
4693 @heading with-foreign-pointer
4695 @Macro{with-foreign-pointer (var size &optional size-var) &body body}
4697 @subheading Arguments and Values
4708 A list of forms to be executed.
4711 @subheading Description
4712 The @code{with-foreign-pointer} macro, binds @var{var} to @var{size}
4713 bytes of foreign memory during @var{body}. The pointer in @var{var}
4714 is invalid beyond the dynamic extend of @var{body} and may be
4715 stack-allocated if supported by the implementation.
4717 If @var{size-var} is supplied, it will be bound to @var{size} during
4720 @subheading Examples
4723 CFFI> (with-foreign-pointer (string 4 size)
4724 (setf (mem-ref string :char (1- size)) 0)
4725 (lisp-string-to-foreign "Popcorns" string size)
4726 (loop for i from 0 below size
4727 collect (code-char (mem-ref string :char i))))
4728 @result{} (#\P #\o #\p #\Null)
4731 @subheading See Also
4732 @seealso{foreign-alloc} @*
4733 @seealso{foreign-free}
4736 @c ===================================================================
4739 @node Strings, Variables, Pointers, Top
4742 As with many languages, Lisp and C have special support for logical
4743 arrays of characters, going so far as to give them a special name,
4744 ``strings''. In that spirit, @cffi{} provides special support for
4745 translating between Lisp and C strings.
4747 The @code{:string} type and the symbols related below also serve as an
4748 example of what you can do portably with @cffi{}; were it not
4749 included, you could write an equally functional @file{strings.lisp}
4750 without referring to any implementation-specific symbols.
4755 * *default-foreign-encoding*::
4756 * foreign-string-alloc::
4757 * foreign-string-free::
4758 * foreign-string-to-lisp::
4759 * lisp-string-to-foreign::
4760 * with-foreign-string::
4761 * with-foreign-strings::
4762 * with-foreign-pointer-as-string::
4766 @c ===================================================================
4767 @c *DEFAULT-FOREIGN-ENCODING*
4770 @node *default-foreign-encoding*, foreign-string-alloc, Strings, Strings
4771 @heading *default-foreign-encoding*
4774 @Variable{*default-foreign-encoding*}
4776 @subheading Value type
4780 @subheading Initial value
4784 @subheading Description
4786 This special variable holds the default foreign encoding.
4788 @subheading Examples
4791 CFFI> *default-foreign-encoding*
4793 CFFI> (foreign-funcall "strdup" (:string :encoding :utf-16) "foo" :string)
4795 CFFI> (let ((*default-foreign-encoding* :utf-16))
4796 (foreign-funcall "strdup" (:string :encoding :utf-16) "foo" :string))
4800 @subheading See also
4802 @seealso{Other Types} (@code{:string} type) @*
4803 @seealso{foreign-string-alloc} @*
4804 @seealso{foreign-string-to-lisp} @*
4805 @seealso{lisp-string-to-foreign} @*
4806 @seealso{with-foreign-string} @*
4807 @seealso{with-foreign-pointer-as-string}
4810 @c ===================================================================
4811 @c FOREIGN-STRING-ALLOC
4814 @node foreign-string-alloc, foreign-string-free, *default-foreign-encoding*, Strings
4815 @heading foreign-string-alloc
4817 @Function{foreign-string-alloc string &key encoding null-terminated-p @
4818 start end @res{} pointer}
4820 @subheading Arguments and Values
4826 @item @var{encoding}
4827 Foreign encoding. Defaults to @code{*default-foreign-encoding*}.
4829 @item @var{null-terminated-p}
4830 Boolean, defaults to true.
4832 @item @var{start}, @var{end}
4833 Bounding index designators of @var{string}. 0 and @code{nil}, by
4837 A pointer to the newly allocated foreign string.
4840 @subheading Description
4841 The @code{foreign-string-alloc} function allocates foreign memory
4842 holding a copy of @var{string} converted using the specified
4843 @var{encoding}. @var{Start} specifies an offset into @var{string} and
4844 @var{end} marks the position following the last element of the foreign
4847 This string must be freed with @code{foreign-string-free}.
4849 If @var{null-terminated-p} is false, the string will not be
4852 @subheading Examples
4855 CFFI> (defparameter *str* (foreign-string-alloc "Hello, foreign world!"))
4856 @result{} #<FOREIGN-ADDRESS #x00400560>
4857 CFFI> (foreign-funcall "strlen" :pointer *str* :int)
4861 @subheading See Also
4862 @seealso{foreign-string-free} @*
4863 @seealso{with-foreign-string}
4864 @c @seealso{:string}
4867 @c ===================================================================
4868 @c FOREIGN-STRING-FREE
4871 @node foreign-string-free, foreign-string-to-lisp, foreign-string-alloc, Strings
4872 @heading foreign-string-free
4874 @Function{foreign-string-free pointer}
4876 @subheading Arguments and Values
4880 A pointer to a string allocated by @code{foreign-string-alloc}.
4883 @subheading Description
4884 The @code{foreign-string-free} function frees a foreign string
4885 allocated by @code{foreign-string-alloc}.
4887 @subheading Examples
4889 @subheading See Also
4890 @seealso{foreign-string-alloc}
4893 @c ===================================================================
4894 @c FOREIGN-STRING-TO-LISP
4897 @node foreign-string-to-lisp, lisp-string-to-foreign, foreign-string-free, Strings
4898 @heading foreign-string-to-lisp
4900 @Function{foreign-string-to-lisp ptr &key offset count max-chars @
4901 encoding @res{} string}
4903 @subheading Arguments and Values
4910 An integer greater than or equal to 0. Defauls to 0.
4913 Either @code{nil} (the default), or an integer greater than or equal to 0.
4916 An integer greater than or equal to 0.
4917 @code{(1- array-total-size-limit)}, by default.
4920 Foreign encoding. Defaults to @code{*default-foreign-encoding*}.
4926 @subheading Description
4927 The @code{foreign-string-to-lisp} function converts at most
4928 @var{count} octets from @var{ptr} into a Lisp string, using the
4929 defined @var{encoding}.
4931 If @var{count} is @code{nil} (the default), characters are copied
4932 until @var{max-chars} is reached or a @code{NULL} character is found.
4934 If @var{ptr} is a null pointer, returns @code{nil}.
4936 Note that the @code{:string} type will automatically convert between
4937 Lisp strings and foreign strings.
4939 @subheading Examples
4942 CFFI> (foreign-funcall "getenv" :string "HOME" :pointer)
4943 @result{} #<FOREIGN-ADDRESS #xBFFFFFD5>
4944 CFFI> (foreign-string-to-lisp *)
4945 @result{} "/Users/luis"
4948 @subheading See Also
4949 @seealso{lisp-string-to-foreign} @*
4950 @seealso{foreign-string-alloc}
4951 @c @seealso{:string}
4954 @c ===================================================================
4955 @c LISP-STRING-TO-FOREIGN
4958 @node lisp-string-to-foreign, with-foreign-string, foreign-string-to-lisp, Strings
4959 @heading lisp-string-to-foreign
4961 @Function{lisp-string-to-foreign string buffer bufsize &key start @
4962 end offset encoding @res{} buffer}
4964 @subheading Arguments and Values
4976 @item @var{start}, @var{end}
4977 Bounding index designators of @var{string}. 0 and @code{nil}, by
4981 An integer greater than or equal to 0. Defauls to 0.
4983 @item @var{encoding}
4984 Foreign encoding. Defaults to @code{*default-foreign-encoding*}.
4987 @subheading Description
4988 The @code{lisp-string-to-foreign} function copies at most
4989 @var{bufsize}-1 octets from a Lisp @var{string} using the specified
4990 @var{encoding} into @var{buffer}+@var{offset}. The foreign string will
4993 @var{Start} specifies an offset into @var{string} and
4994 @var{end} marks the position following the last element of the foreign
4997 @subheading Examples
5000 CFFI> (with-foreign-pointer-as-string (str 255)
5001 (lisp-string-to-foreign "Hello, foreign world!" str 6))
5005 @subheading See Also
5006 @seealso{foreign-string-alloc} @*
5007 @seealso{foreign-string-to-lisp} @*
5008 @seealso{with-foreign-pointer-as-string}
5011 @c ===================================================================
5012 @c WITH-FOREIGN-STRING
5015 @node with-foreign-string, with-foreign-pointer-as-string, lisp-string-to-foreign, Strings
5016 @heading with-foreign-string, with-foreign-strings
5018 @Macro{with-foreign-string (var-or-vars string &rest args) &body body}
5020 @anchor{with-foreign-strings}
5021 @Macro{with-foreign-strings (bindings) &body body}
5023 var-or-vars ::= var | (var &optional octet-size-var)
5024 bindings ::= @{(var-or-vars string &rest args)@}*
5026 @subheading Arguments and Values
5029 @item @var{var}, @var{byte-size-var}
5036 A list of forms to be executed.
5039 @subheading Description
5040 The @code{with-foreign-string} macro will bind @var{var} to a newly
5041 allocated foreign string containing @var{string}. @var{Args} is passed
5042 to the underlying @code{foreign-string-alloc} call.
5044 If @var{octet-size-var} is provided, it will be bound the length of
5045 foreign string in octets including the null terminator.
5047 @subheading Examples
5050 CFFI> (with-foreign-string (foo "12345")
5051 (foreign-funcall "strlen" :pointer foo :int))
5054 CFFI> (let ((array (coerce #(84 117 114 97 110 103 97)
5055 '(array (unsigned-byte 8)))))
5056 (with-foreign-string (foreign-string array)
5057 (foreign-string-to-lisp foreign-string)))
5061 @subheading See Also
5062 @seealso{foreign-string-alloc} @*
5063 @seealso{with-foreign-pointer-as-string}
5066 @c ===================================================================
5067 @c WITH-FOREIGN-POINTER-AS-STRING
5070 @node with-foreign-pointer-as-string, , with-foreign-string, Strings
5071 @heading with-foreign-pointer-as-string
5073 @Macro{with-foreign-pointer-as-string (var size &optional size-var @
5074 &rest args) &body body @res{} string}
5076 @subheading Arguments and Values
5086 List of forms to be executed.
5089 @subheading Description
5090 The @code{with-foreign-pointer-as-string} macro is similar to
5091 @code{with-foreign-pointer} except that @var{var} is used as the
5092 returned value of an implicit @code{progn} around @var{body}, after
5093 being converted to a Lisp string using the provided @var{args}.
5095 @subheading Examples
5098 CFFI> (with-foreign-pointer-as-string (str 6 str-size :encoding :ascii)
5099 (lisp-string-to-foreign "Hello, foreign world!" str str-size))
5103 @subheading See Also
5104 @seealso{foreign-string-alloc} @*
5105 @seealso{with-foreign-string}
5108 @c ===================================================================
5109 @c CHAPTER: Variables
5111 @node Variables, Functions, Strings, Top
5122 @c ===================================================================
5126 @node defcvar, get-var-pointer, Variables, Variables
5129 @Macro{defcvar name-and-options type &optional documentation @res{} lisp-name}
5131 @var{name-and-options} ::= name | (name &key read-only (library :default)) @*
5132 @var{name} ::= lisp-name [foreign-name] | foreign-name [lisp-name]
5134 @subheading Arguments and Values
5138 A string denoting a foreign function.
5141 A symbol naming the Lisp function to be created.
5150 A Lisp string; not evaluated.
5153 @subheading Description
5154 The @code{defcvar} macro defines a symbol macro @var{lisp-name} that looks
5155 up @var{foreign-name} and dereferences it acording to @var{type}. It
5156 can also be @code{setf}ed, unless @var{read-only} is true, in which
5157 case an error will be signaled.
5159 When one of @var{lisp-name} or @var{foreign-name} is omitted, the
5160 other is automatically derived using the following rules:
5164 Foreign names are converted to Lisp names by uppercasing, replacing
5165 underscores with hyphens, and wrapping around asterisks.
5167 Lisp names are converted to foreign names by lowercasing, replacing
5168 hyphens with underscores, and removing asterisks, if any.
5171 @subheading Examples
5174 CFFI> (defcvar "errno" :int)
5176 CFFI> (foreign-funcall "strerror" :int *errno* :string)
5177 @result{} "Inappropriate ioctl for device"
5178 CFFI> (setf *errno* 1)
5180 CFFI> (foreign-funcall "strerror" :int *errno* :string)
5181 @result{} "Operation not permitted"
5184 Trying to modify a read-only foreign variable:
5187 CFFI> (defcvar ("errno" +error-number+ :read-only t) :int)
5188 @result{} +ERROR-NUMBER+
5189 CFFI> (setf +error-number+ 12)
5190 ;; @lispcmt{@error{} Trying to modify read-only foreign var: +ERROR-NUMBER+.}
5193 @emph{Note that accessing @code{errno} this way won't work with every
5194 implementation of the C standard library.}
5196 @subheading See Also
5197 @seealso{get-var-pointer}
5200 @c ===================================================================
5204 @node get-var-pointer, , defcvar, Variables
5205 @heading get-var-pointer
5207 @Function{get-var-pointer symbol @res{} pointer}
5209 @subheading Arguments and Values
5213 A symbol denoting a foreign variable defined with @code{defcvar}.
5219 @subheading Description
5220 The function @code{get-var-pointer} will return a @var{pointer} to the
5221 foreign global variable @var{symbol} previously defined with
5224 @subheading Examples
5227 CFFI> (defcvar "errno" :int :read-only t)
5231 CFFI> (get-var-pointer '*errno*)
5232 @result{} #<A Mac Pointer #xA0008130>
5233 CFFI> (mem-ref * :int)
5237 @subheading See Also
5241 @c ===================================================================
5242 @c CHAPTER: Functions
5244 @node Functions, Libraries, Variables, Top
5248 @c * Defining Foreign Functions::
5249 @c * Calling Foreign Functions::
5255 * foreign-funcall-pointer::
5256 * foreign-funcall-varargs::
5257 * foreign-funcall-pointer-varargs::
5258 * translate-camelcase-name::
5259 * translate-name-from-foreign::
5260 * translate-name-to-foreign::
5261 * translate-underscore-separated-name::
5264 @c @node Calling Foreign Functions
5265 @c @section Calling Foreign Functions
5267 @c @node Defining Foreign Functions
5268 @c @section Defining Foreign Functions
5271 @c ===================================================================
5275 @node defcfun, foreign-funcall, Functions, Functions
5278 @Macro{defcfun name-and-options return-type &body [docstring] arguments [&rest] @
5281 @var{name-and-options} ::= @var{name} | (@var{name} &key @var{library} @var{convention}) @*
5282 @var{name} ::= @var{lisp-name} [@var{foreign-name}] | @var{foreign-name} [@var{lisp-name}] @*
5283 @var{arguments} ::= @{ (@var{arg-name} @var{arg-type}) @}* @*
5285 @subheading Arguments and Values
5289 A string denoting a foreign function.
5292 A symbol naming the Lisp function to be created.
5302 One of @code{:cdecl} (default) or @code{:stdcall}.
5305 A symbol designating a foreign library.
5308 A documentation string.
5311 @subheading Description
5312 The @code{defcfun} macro provides a declarative interface for defining
5313 Lisp functions that call foreign functions.
5315 When one of @var{lisp-name} or @var{foreign-name} is omitted, the
5316 other is automatically derived using the following rules:
5320 Foreign names are converted to Lisp names by uppercasing and replacing
5321 underscores with hyphens.
5323 Lisp names are converted to foreign names by lowercasing and replacing
5324 hyphens with underscores.
5327 If you place the symbol @code{&rest} in the end of the argument list
5328 after the fixed arguments, @code{defcfun} will treat the foreign
5329 function as a @strong{variadic function}. The variadic arguments
5330 should be passed in a way similar to what @code{foreign-funcall} would
5331 expect. Unlike @code{foreign-funcall} though, @code{defcfun} will take
5332 care of doing argument promotion. Note that in this case
5333 @code{defcfun} will generate a Lisp @emph{macro} instead of a
5334 function and will only work for Lisps that support
5335 @code{foreign-funcall.}
5337 If a foreign structure is to be passed or returned by value (that is,
5338 the type is of the form @code{(:struct ...)}), then the cffi-libffi system
5339 must be loaded, which in turn depends on
5340 @uref{http://sourceware.org/libffi/,libffi}, including the header files.
5341 Failure to load that system will result in an error.
5342 Variadic functions cannot at present accept or return structures by
5345 @subheading Examples
5348 (defcfun "strlen" :int
5349 "Calculate the length of a string."
5352 CFFI> (strlen "123")
5357 (defcfun ("abs" c-abs) :int (n :int))
5363 Function without arguments:
5366 (defcfun "rand" :int)
5369 @result{} 1804289383
5372 Variadic function example:
5375 (defcfun "sprintf" :int
5380 CFFI> (with-foreign-pointer-as-string (s 100)
5381 (sprintf s "%c %d %.2f %s" :char 90 :short 42 :float pi
5382 :string "super-locrian"))
5383 @result{} "A 42 3.14 super-locrian"
5386 @subheading See Also
5387 @seealso{foreign-funcall} @*
5388 @seealso{foreign-funcall-pointer} @*
5389 @seealso{foreign-funcall-varargs} @*
5390 @seealso{foreign-funcall-pointer-varargs}
5393 @c ===================================================================
5397 @node foreign-funcall, foreign-funcall-pointer, defcfun, Functions
5398 @heading foreign-funcall
5400 @Macro{foreign-funcall name-and-options &rest arguments @res{} return-value}
5402 @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
5403 @var{name-and-options} ::= @var{name} | (@var{name} &key @var{library} @var{convention}) @*
5405 @subheading Arguments and Values
5415 An argument of type @var{arg-type}.
5418 A foreign type, @code{:void} by default.
5424 A lisp symbol; not evaluated.
5427 One of @code{:cdecl} (default) or @code{:stdcall}.
5430 @subheading Description
5431 The @code{foreign-funcall} macro is the main primitive for calling
5434 If a foreign structure is to be passed or returned by value (that is,
5435 the type is of the form @code{(:struct ...)}), then the cffi-libffi system
5436 must be loaded, which in turn depends on
5437 @uref{http://sourceware.org/libffi/,libffi}, including the header files.
5438 Failure to load that system will result in an error.
5439 Variadic functions cannot at present accept or return structures by
5442 @emph{Note: The return value of foreign-funcall on functions with a
5443 :void return type is still undefined.}
5445 @subheading Implementation-specific Notes
5448 Corman Lisp does not support @code{foreign-funcall}. On
5449 implementations that @strong{don't} support @code{foreign-funcall}
5450 @code{cffi-sys::no-foreign-funcall} will be present in
5451 @code{*features*}. Note: in these Lisps you can still use the
5452 @code{defcfun} interface.
5455 @subheading Examples
5458 CFFI> (foreign-funcall "strlen" :string "foo" :int)
5465 void print_number(int n)
5467 printf("N: %d\n", n);
5472 CFFI> (foreign-funcall "print_number" :int 123456)
5481 CFFI> (foreign-funcall "print_number" :int 123456 :void)
5487 CFFI> (foreign-funcall "printf" :string (format nil "%s: %d.~%")
5488 :string "So long and thanks for all the fish"
5490 @print{} So long and thanks for all the fish: 42.
5494 @subheading See Also
5495 @seealso{defcfun} @*
5496 @seealso{foreign-funcall-pointer}
5499 @c ===================================================================
5500 @c FOREIGN-FUNCALL-POINTER
5503 @node foreign-funcall-pointer, foreign-funcall-varargs, foreign-funcall, Functions
5504 @heading foreign-funcall-pointer
5506 @Macro{foreign-funcall-pointer pointer options &rest arguments @res{} return-value}
5508 @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
5509 @var{options} ::= (&key @var{convention}) @*
5511 @subheading Arguments and Values
5521 An argument of type @var{arg-type}.
5524 A foreign type, @code{:void} by default.
5530 One of @code{:cdecl} (default) or @code{:stdcall}.
5533 @subheading Description
5534 The @code{foreign-funcall} macro is the main primitive for calling
5537 @emph{Note: The return value of foreign-funcall on functions with a
5538 :void return type is still undefined.}
5540 @subheading Implementation-specific Notes
5543 Corman Lisp does not support @code{foreign-funcall}. On
5544 implementations that @strong{don't} support @code{foreign-funcall}
5545 @code{cffi-sys::no-foreign-funcall} will be present in
5546 @code{*features*}. Note: in these Lisps you can still use the
5547 @code{defcfun} interface.
5550 @subheading Examples
5553 CFFI> (foreign-funcall-pointer (foreign-symbol-pointer "abs") ()
5558 @subheading See Also
5559 @seealso{defcfun} @*
5560 @seealso{foreign-funcall}
5563 @c ===================================================================
5564 @c FOREIGN-FUNCALL-VARARGS
5567 @node foreign-funcall-varargs, foreign-funcall-pointer-varargs, foreign-funcall-pointer, Functions
5568 @heading foreign-funcall-varargs
5570 @Macro{foreign-funcall-varargs name-and-options (fixed-arguments) &rest arguments @res{} return-value}
5572 @var{fixed-arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
5573 @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
5574 @var{name-and-options} ::= @var{name} | (@var{name} &key @var{library} @var{convention}) @*
5576 @subheading Arguments and Values
5586 An argument of type @var{arg-type}.
5589 A foreign type, @code{:void} by default.
5595 A lisp symbol; not evaluated.
5598 One of @code{:cdecl} (default) or @code{:stdcall}.
5601 @subheading Description
5602 The @code{foreign-funcall-varargs} macro is the main primitive for
5603 calling foreign variadic functions. It behaves similarily to
5604 @code{foreign-funcall} except @code{fixed-arguments} are distinguished
5605 from the remaining arguments.
5607 @subheading Examples
5610 CFFI> (with-foreign-pointer-as-string (s 100)
5611 (setf (mem-ref s :char) 0)
5612 (foreign-funcall-varargs
5613 "sprintf" (:pointer s :string) "%.2f")
5614 :double (coerce pi 'double-float) :int))
5619 @c ===================================================================
5620 @c FOREIGN-FUNCALL-POINTER-VARARGS
5623 @node foreign-funcall-pointer-varargs, translate-camelcase-name, foreign-funcall-varargs, Functions
5624 @heading foreign-funcall-pointer-varargs
5626 @Macro{foreign-funcall-pointer-varargs pointer options (fixed-arguments) &rest arguments @res{} return-value}
5628 @var{fixed-arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
5629 @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
5630 @var{options} ::= (&key @var{convention}) @*
5632 @subheading Arguments and Values
5642 An argument of type @var{arg-type}.
5645 A foreign type, @code{:void} by default.
5651 One of @code{:cdecl} (default) or @code{:stdcall}.
5654 @subheading Description
5655 The @code{foreign-funcall-pointer-varargs} macro is the main primitive
5656 for calling foreign variadic functions. It behaves similarily to
5657 @code{foreign-funcall-pointer} except @code{fixed-arguments} are
5658 distinguished from the remaining arguments.
5660 @subheading Examples
5663 CFFI> (with-foreign-pointer-as-string (s 100)
5664 (setf (mem-ref s :char) 0)
5665 (foreign-funcall-pointer-varargs
5666 (foreign-symbol-pointer "sprintf") () (:pointer s :string "%.2f")
5667 :double (coerce pi 'double-float) :int))
5672 @c ===================================================================
5673 @c TRANSLATE-CAMELCASE-NAME
5676 @node translate-camelcase-name, translate-name-from-foreign, foreign-funcall-pointer-varargs, Functions
5677 @heading translate-camelcase-name
5679 @Function{translate-camelcase-name name &key upper-initial-p special-words @res{} return-value}
5681 @subheading Arguments and Values
5685 Either a symbol or a string.
5687 @item upper-initial-p
5688 A generalized boolean.
5694 If @var{name} is a symbol, this is a string, and vice versa.
5697 @subheading Description
5698 @code{translate-camelcase-name} is a helper function for
5699 specializations of @code{translate-name-from-foreign} and
5700 @code{translate-name-to-foreign}. It handles the common case of
5701 converting between foreign camelCase names and lisp
5702 names. @var{upper-initial-p} indicates whether the first letter of the
5703 foreign name should be uppercase. @var{special-words} is a list of
5704 strings that should be treated atomically in translation. This list is
5707 @subheading Examples
5710 CFFI> (translate-camelcase-name some-xml-function)
5711 @result{} "someXmlFunction"
5712 CFFI> (translate-camelcase-name some-xml-function :upper-initial-p t)
5713 @result{} "SomeXmlFunction"
5714 CFFI> (translate-camelcase-name some-xml-function :special-words '("XML"))
5715 @result{} "someXMLFunction"
5716 CFFI> (translate-camelcase-name "someXMLFunction")
5717 @result{} SOME-X-M-L-FUNCTION
5718 CFFI> (translate-camelcase-name "someXMLFunction" :special-words '("XML"))
5719 @result{} SOME-XML-FUNCTION
5722 @subheading See Also
5723 @seealso{translate-name-from-foreign} @*
5724 @seealso{translate-name-to-foreign} @*
5725 @seealso{translate-underscore-separated-name}
5728 @c ===================================================================
5729 @c TRANSLATE-NAME-FROM-FOREIGN
5732 @node translate-name-from-foreign, translate-name-to-foreign, translate-camelcase-name, Functions
5733 @heading translate-name-from-foreign
5735 @Function{translate-name-from-foreign foreign-name package &optional varp @res{} symbol}
5737 @subheading Arguments and Values
5741 A string denoting a foreign function.
5747 A generalized boolean.
5750 The Lisp symbol to be used a function name.
5753 @subheading Description
5754 @code{translate-name-from-foreign} is used by @ref{defcfun} to handle
5755 the conversion of foreign names to lisp names. By default, it
5756 translates using @ref{translate-underscore-separated-name}. However,
5757 you can create specialized methods on this function to make
5758 translating more closely match the foreign library's naming
5761 Specialize @var{package} on some package. This allows other packages
5762 to load libraries with different naming conventions.
5764 @subheading Examples
5767 CFFI> (defcfun "someXmlFunction" ...)
5768 @result{} SOMEXMLFUNCTION
5769 CFFI> (defmethod translate-name-from-foreign ((spec string)
5770 (package (eql *package*))
5772 (let ((name (translate-camelcase-name spec)))
5773 (if varp (intern (format nil "*~a*" name)) name)))
5774 @result{} #<STANDARD-METHOD TRANSLATE-NAME-FROM-FOREIGN (STRING (EQL #<Package "SOME-PACKAGE">))>
5775 CFFI> (defcfun "someXmlFunction" ...)
5776 @result{} SOME-XML-FUNCTION
5779 @subheading See Also
5780 @seealso{defcfun} @*
5781 @seealso{translate-camelcase-name} @*
5782 @seealso{translate-name-to-foreign} @*
5783 @seealso{translate-underscore-separated-name}
5786 @c ===================================================================
5787 @c TRANSLATE-NAME-TO-FOREIGN
5790 @node translate-name-to-foreign, translate-underscore-separated-name, translate-name-from-foreign, Functions
5791 @heading translate-name-to-foreign
5793 @Function{translate-name-to-foreign lisp-name package &optional varp @res{} string}
5795 @subheading Arguments and Values
5799 A symbol naming the Lisp function to be created.
5805 A generalized boolean.
5808 The string representing the foreign function name.
5811 @subheading Description
5812 @code{translate-name-to-foreign} is used by @ref{defcfun} to handle
5813 the conversion of lisp names to foreign names. By default, it
5814 translates using @ref{translate-underscore-separated-name}. However,
5815 you can create specialized methods on this function to make
5816 translating more closely match the foreign library's naming
5819 Specialize @var{package} on some package. This allows other packages
5820 to load libraries with different naming conventions.
5822 @subheading Examples
5825 CFFI> (defcfun some-xml-function ...)
5826 @result{} "some_xml_function"
5827 CFFI> (defmethod translate-name-to-foreign ((spec symbol)
5828 (package (eql *package*))
5830 (let ((name (translate-camelcase-name spec)))
5831 (if varp (subseq name 1 (1- (length name))) name)))
5832 @result{} #<STANDARD-METHOD TRANSLATE-NAME-TO-FOREIGN (STRING (EQL #<Package "SOME-PACKAGE">))>
5833 CFFI> (defcfun some-xml-function ...)
5834 @result{} "someXmlFunction"
5837 @subheading See Also
5838 @seealso{defcfun} @*
5839 @seealso{translate-camelcase-name} @*
5840 @seealso{translate-name-from-foreign} @*
5841 @seealso{translate-underscore-separated-name}
5844 @c ===================================================================
5845 @c TRANSLATE-UNDERSCORE-SEPARATED-NAME
5848 @node translate-underscore-separated-name, , translate-name-to-foreign, Functions
5849 @heading translate-underscore-separated-name
5851 @Function{translate-underscore-separated-name name @res{} return-value}
5853 @subheading Arguments and Values
5857 Either a symbol or a string.
5860 If @var{name} is a symbol, this is a string, and vice versa.
5863 @subheading Description
5864 @code{translate-underscore-separated-name} is a helper function for
5865 specializations of @ref{translate-name-from-foreign} and
5866 @ref{translate-name-to-foreign}. It handles the common case of
5867 converting between foreign underscore_separated names and lisp names.
5869 @subheading Examples
5872 CFFI> (translate-underscore-separated-name some-xml-function)
5873 @result{} "some_xml_function"
5874 CFFI> (translate-camelcase-name "some_xml_function")
5875 @result{} SOME-XML-FUNCTION
5878 @subheading See Also
5879 @seealso{translate-name-from-foreign} @*
5880 @seealso{translate-name-to-foreign} @*
5881 @seealso{translate-camelcase-name}
5884 @c ===================================================================
5885 @c CHAPTER: Libraries
5887 @node Libraries, Callbacks, Functions, Top
5891 * Defining a library::
5892 * Library definition style::
5896 * close-foreign-library:: Close a foreign library.
5897 * *darwin-framework-directories*:: Search path for Darwin frameworks.
5898 * define-foreign-library:: Explain how to load a foreign library.
5899 * *foreign-library-directories*:: Search path for shared libraries.
5900 * load-foreign-library:: Load a foreign library.
5901 * load-foreign-library-error:: Signalled on failure of its namesake.
5902 * use-foreign-library:: Load a foreign library when needed.
5906 @node Defining a library, Library definition style, Libraries, Libraries
5907 @section Defining a library
5909 Almost all foreign code you might want to access exists in some kind
5910 of shared library. The meaning of @dfn{shared library} varies among
5911 platforms, but for our purposes, we will consider it to include
5912 @file{.so} files on @sc{unix}, frameworks on Darwin (and derivatives
5913 like Mac @acronym{OS X}), and @file{.dll} files on Windows.
5915 Bringing one of these libraries into the Lisp image is normally a
5920 Describe to @cffi{} how to load the library at some future point,
5921 depending on platform and other factors, with a
5922 @code{define-foreign-library} top-level form.
5925 Load the library so defined with either a top-level
5926 @code{use-foreign-library} form or by calling the function
5927 @code{load-foreign-library}.
5930 @xref{Tutorial-Loading,, Loading foreign libraries}, for a working
5931 example of the above two steps.
5934 @node Library definition style, close-foreign-library, Defining a library, Libraries
5935 @section Library definition style
5937 Looking at the @code{libcurl} library definition presented earlier,
5938 you may ask why we did not simply do this:
5941 (define-foreign-library libcurl
5942 (t (:default "libcurl")))
5946 Indeed, this would work just as well on the computer on which I tested
5947 the tutorial. There are a couple of good reasons to provide the
5948 @file{.so}'s current version number, however. Namely, the versionless
5949 @file{.so} is not packaged on most @sc{unix} systems along with the
5950 actual, fully-versioned library; instead, it is included in the
5951 ``development'' package along with C headers and static @file{.a}
5954 The reason @cffi{} does not try to account for this lies in the
5955 meaning of the version numbers. A full treatment of shared library
5956 versions is beyond this manual's scope; see @ref{Versioning,, Library
5957 interface versions, libtool, @acronym{GNU} Libtool}, for helpful
5958 information for the unfamiliar. For our purposes, consider that a
5959 mismatch between the library version with which you tested and the
5960 installed library version may cause undefined
5961 behavior.@footnote{Windows programmers may chafe at adding a
5962 @sc{unix}-specific clause to @code{define-foreign-library}. Instead,
5963 ask why the Windows solution to library incompatibility is ``include
5964 your own version of every library you use with every program''.}
5966 @impnote{Maybe some notes should go here about OS X, which I know
5967 little about. --stephen}
5970 @c ===================================================================
5971 @c CLOSE-FOREIGN-LIBRARY
5974 @node close-foreign-library, *darwin-framework-directories*, Library definition style, Libraries
5975 @heading close-foreign-library
5977 @Function{close-foreign-library library @res{} success}
5979 @subheading Arguments and Values
5983 A symbol or an instance of @code{foreign-library}.
5989 @subheading Description
5991 Closes @var{library} which can be a symbol designating a library
5992 define through @code{define-foreign-library} or an instance of
5993 @code{foreign-library} as returned by @code{load-foreign-library}.
5995 @c @subheading Examples
5996 @c @xref{Tutorial-Loading,, Loading foreign libraries}.
5998 @subheading See Also
6000 @seealso{define-foreign-library} @*
6001 @seealso{load-foreign-library} @*
6002 @seealso{use-foreign-library}
6005 @c ===================================================================
6006 @c *DARWIN-FRAMEWORK-DIRECTORIES*
6009 @node *darwin-framework-directories*, define-foreign-library, close-foreign-library, Libraries
6010 @heading *darwin-framework-directories*
6013 @Variable{*darwin-framework-directories*}
6015 @subheading Value type
6017 A list, in which each element is a string, a pathname, or a simple
6020 @subheading Initial value
6022 A list containing the following, in order: an expression corresponding
6023 to Darwin path @file{~/Library/Frameworks/},
6024 @code{#P"/Library/Frameworks/"}, and
6025 @code{#P"/System/Library/Frameworks/"}.
6027 @subheading Description
6029 The meaning of ``simple Lisp expression'' is explained in
6030 @ref{*foreign-library-directories*}. In contrast to that variable,
6031 this is not a fallback search path; the default value described above
6032 is intended to be a reasonably complete search path on Darwin systems.
6034 @subheading Examples
6037 CFFI> (let ((lib (load-foreign-library '(:framework "OpenGL"))))
6038 (foreign-library-pathname lib))
6039 @result{} #P"/System/Library/Frameworks/OpenGL.framework/OpenGL"
6042 @subheading See also
6044 @seealso{*foreign-library-directories*} @*
6045 @seealso{define-foreign-library}
6048 @c ===================================================================
6049 @c DEFINE-FOREIGN-LIBRARY
6052 @node define-foreign-library, *foreign-library-directories*, *darwin-framework-directories*, Libraries
6053 @heading define-foreign-library
6057 @Macro{define-foreign-library name-and-options @{ load-clause @}* @res{} name}
6059 name-and-options ::= name | (name &key convention search-path)
6060 load-clause ::= (feature library &key convention search-path)
6062 @subheading Arguments and Values
6069 A feature expression.
6072 A library designator.
6075 One of @code{:cdecl} (default) or @code{:stdcall}
6078 A path or list of paths where the library will be searched if not found in
6079 system-global directories. Paths specified in a load clause take priority over
6080 paths specified as library option, with *foreign-library-directories* having
6084 @subheading Description
6086 Creates a new library designator called @var{name}. The
6087 @var{load-clause}s describe how to load that designator when passed to
6088 @code{load-foreign-library} or @code{use-foreign-library}.
6090 When trying to load the library @var{name}, the relevant function
6091 searches the @var{load-clause}s in order for the first one where
6092 @var{feature} evaluates to true. That happens for any of the
6093 following situations:
6097 If @var{feature} is a symbol present in @code{common-lisp:*features*}.
6100 If @var{feature} is a list, depending on @code{(first @var{feature})},
6105 All of the feature expressions in @code{(rest @var{feature})} are
6109 At least one of the feature expressions in @code{(rest @var{feature})}
6113 The feature expression @code{(second @var{feature})} is not true.
6117 Finally, if @var{feature} is @code{t}, this @var{load-clause} is
6118 picked unconditionally.
6121 Upon finding the first true @var{feature}, the library loader then
6122 loads the @var{library}. The meaning of ``library designator'' is
6123 described in @ref{load-foreign-library}.
6125 Functions associated to a library defined by
6126 @code{define-foreign-library} (e.g. through @code{defcfun}'s
6127 @code{:library} option, will inherit the library's options. The
6128 precedence is as follows:
6132 @code{defcfun}/@code{foreign-funcall} specific options;
6135 @var{load-clause} options;
6138 global library options (the @var{name-and-options} argument)
6142 @subheading Examples
6144 @xref{Tutorial-Loading,, Loading foreign libraries}.
6147 @subheading See Also
6149 @seealso{close-foreign-library} @*
6150 @seealso{load-foreign-library}
6153 @c ===================================================================
6154 @c *FOREIGN-LIBRARY-DIRECTORIES*
6157 @node *foreign-library-directories*, load-foreign-library, define-foreign-library, Libraries
6158 @heading *foreign-library-directories*
6161 @Variable{*foreign-library-directories*}
6163 @subheading Value type
6165 A list, in which each element is a string, a pathname, or a simple
6168 @subheading Initial value
6172 @subheading Description
6174 You should not have to use this variable.
6176 Most, if not all, Lisps supported by @cffi{} have a reasonable default
6177 search algorithm for foreign libraries. For example, Lisps for
6178 @sc{unix} usually call
6179 @uref{http://www.opengroup.org/onlinepubs/009695399/functions/dlopen.html,,
6180 @code{dlopen(3)}}, which in turn looks in the system library
6181 directories. Only if that fails does @cffi{} look for the named
6182 library file in these directories, and load it from there if found.
6184 Thus, this is intended to be a @cffi{}-only fallback to the library
6185 search configuration provided by your operating system. For example,
6186 if you distribute a foreign library with your Lisp package, you can
6187 add the library's containing directory to this list and portably
6188 expect @cffi{} to find it.
6190 A @dfn{simple Lisp expression} is intended to provide functionality
6191 commonly used in search paths such as
6192 @acronym{ASDF}'s@footnote{@xref{Using asdf to load systems,,, asdf,
6193 asdf: another system definition facility}, for information on
6194 @code{asdf:*central-registry*}.}, and is defined recursively as
6195 follows:@footnote{See @code{mini-eval} in @file{libraries.lisp} for
6196 the source of this definition. As is always the case with a Lisp
6197 @code{eval}, it's easier to understand the Lisp definition than the
6202 A list, whose @samp{first} is a function designator, and whose
6203 @samp{rest} is a list of simple Lisp expressions to be evaluated and
6204 passed to the so-designated function. The result is the result of the
6208 A symbol, whose result is its symbol value.
6211 Anything else evaluates to itself.
6214 The result of evaluating the @dfn{simple Lisp expression} should yield
6215 a @emph{designator} for a @emph{list} of @emph{pathname designators}.
6217 @strong{Note}: in Common Lisp, @code{#p"/foo/bar"} designates the
6218 @emph{bar} file within the @emph{/foo} directory whereas
6219 @code{#p"/foo/bar/"} designates the @emph{/foo/bar} directory. Keep
6220 that in mind when customising the value of
6221 @code{*foreign-library-directories*}.
6224 @subheading Examples
6228 @print{} liblibli.so libli.lisp
6232 In @file{libli.lisp}:
6235 (pushnew #P"/home/sirian/lisp/libli/" *foreign-library-directories*
6238 (load-foreign-library '(:default "liblibli"))
6242 The following example would achieve the same effect:
6245 (pushnew '(merge-pathnames #p"lisp/libli/" (user-homedir-pathname))
6246 *foreign-library-directories*
6248 @result{} ((MERGE-PATHNAMES #P"lisp/libli/" (USER-HOMEDIR-PATHNAME)))
6250 (load-foreign-library '(:default "liblibli"))
6253 @subheading See also
6255 @seealso{*darwin-framework-directories*} @*
6256 @seealso{define-foreign-library}
6259 @c ===================================================================
6260 @c LOAD-FOREIGN-LIBRARY
6263 @node load-foreign-library, load-foreign-library-error, *foreign-library-directories*, Libraries
6264 @heading load-foreign-library
6266 @Function{load-foreign-library library-designator @res{} library}
6268 @subheading Arguments and Values
6271 @item library-designator
6272 A library designator.
6274 @item library-designator
6275 An instance of @code{foreign-library}.
6278 @subheading Description
6280 Load the library indicated by @var{library-designator}. A @dfn{library
6281 designator} is defined as follows:
6285 If a symbol, is considered a name previously defined with
6286 @code{define-foreign-library}.
6289 If a string or pathname, passed as a namestring directly to the
6290 implementation's foreign library loader. If that fails, search the
6291 directories in @code{*foreign-library-directories*} with
6292 @code{cl:probe-file}; if found, the absolute path is passed to the
6293 implementation's loader.
6296 If a list, the meaning depends on @code{(first @var{library})}:
6300 The second list element is taken to be a Darwin framework name, which
6301 is then searched in @code{*darwin-framework-directories*}, and loaded
6305 Each remaining list element, itself a @dfn{library designator}, is loaded in
6306 order, until one succeeds.
6309 The name is transformed according to the platform's naming convention
6310 to shared libraries, and the resultant string is loaded as a @dfn{library
6311 designator}. For example, on @sc{unix}, the name is suffixed with
6316 If the library is already loaded it will be reloaded.
6318 If the load fails, signal a @code{load-foreign-library-error}.
6320 @strong{Please note:} For system libraries, you should not need to
6321 specify the directory containing the library. Each operating system
6322 has its own idea of a default search path, and you should rely on it
6323 when it is reasonable.
6325 @subheading Implementation-specific Notes
6326 On ECL platforms where its dynamic FFI is not supported (ie. when
6327 @code{:dffi} is not present in @code{*features*}),
6328 @code{cffi:load-foreign-library} does not work and you must use ECL's
6329 own @code{ffi:load-foreign-library} with a constant string argument.
6331 @subheading Examples
6333 @xref{Tutorial-Loading,, Loading foreign libraries}.
6335 @subheading See Also
6337 @seealso{close-foreign-library} @*
6338 @seealso{*darwin-framework-directories*} @*
6339 @seealso{define-foreign-library} @*
6340 @seealso{*foreign-library-directories*} @*
6341 @seealso{load-foreign-library-error} @*
6342 @seealso{use-foreign-library}
6345 @c ===================================================================
6346 @c LOAD-FOREIGN-LIBRARY-ERROR
6349 @node load-foreign-library-error, use-foreign-library, load-foreign-library, Libraries
6350 @heading load-foreign-library-error
6354 @Condition{load-foreign-library-error}
6356 @subheading Class precedence list
6358 @code{load-foreign-library-error}, @code{error},
6359 @code{serious-condition}, @code{condition}, @code{t}
6361 @subheading Description
6363 Signalled when a foreign library load completely fails. The exact
6364 meaning of this varies depending on the real conditions at work, but
6365 almost universally, the implementation's error message is useless.
6366 However, @cffi{} does provide the useful restarts @code{retry} and
6367 @code{use-value}; invoke the @code{retry} restart to try loading the
6368 foreign library again, or the @code{use-value} restart to try loading
6369 a different foreign library designator.
6371 @subheading See also
6373 @seealso{load-foreign-library}
6376 @c ===================================================================
6377 @c USE-FOREIGN-LIBRARY
6380 @node use-foreign-library, , load-foreign-library-error, Libraries
6381 @heading use-foreign-library
6385 @Macro{use-foreign-library name}
6387 @subheading Arguments and values
6391 A library designator; unevaluated.
6395 @subheading Description
6397 @xref{load-foreign-library}, for the meaning of ``library
6398 designator''. This is intended to be the top-level form used
6399 idiomatically after a @code{define-foreign-library} form to go ahead
6400 and load the library. @c ; it also sets the ``current foreign library''.
6401 Finally, on implementations where the regular evaluation rule is
6402 insufficient for foreign library loading, it loads it at the required
6403 time.@footnote{Namely, @acronym{CMUCL}. See
6404 @code{use-foreign-library} in @file{libraries.lisp} for details.}
6406 @c current foreign library is a concept created a few hours ago as of
6407 @c this writing. It is not actually used yet, but probably will be.
6409 @subheading Examples
6411 @xref{Tutorial-Loading,, Loading foreign libraries}.
6414 @subheading See also
6416 @seealso{load-foreign-library}
6419 @c ===================================================================
6420 @c CHAPTER: Callbacks
6422 @node Callbacks, The Groveller, Libraries, Top
6434 @c ===================================================================
6438 @node callback, defcallback, Callbacks, Callbacks
6441 @Macro{callback symbol @res{} pointer}
6443 @subheading Arguments and Values
6447 A symbol denoting a callback.
6454 @subheading Description
6455 The @code{callback} macro is analogous to the standard CL special
6456 operator @code{function} and will return a pointer to the callback
6457 denoted by the symbol @var{name}.
6459 @subheading Examples
6462 CFFI> (defcallback sum :int ((a :int) (b :int))
6465 CFFI> (callback sum)
6466 @result{} #<A Mac Pointer #x102350>
6469 @subheading See Also
6470 @seealso{get-callback} @*
6471 @seealso{defcallback}
6474 @c ===================================================================
6478 @node defcallback, get-callback, callback, Callbacks
6479 @heading defcallback
6481 @Macro{defcallback name-and-options return-type arguments &body body @res{} name}
6483 name-and-options ::= name | (name &key convention)
6484 arguments ::= (@{ (arg-name arg-type) @}*)
6486 @subheading Arguments and Values
6490 A symbol naming the callback created.
6493 The foreign type for the callback's return value.
6502 One of @code{:cdecl} (default) or @code{:stdcall}.
6505 @subheading Description
6506 The @code{defcallback} macro defines a Lisp function that can be called
6507 from C. The arguments passed to this function will be converted to the
6508 appropriate Lisp representation and its return value will be converted
6509 to its C representation.
6511 This Lisp function can be accessed by the @code{callback} macro or the
6512 @code{get-callback} function.
6514 @strong{Portability note:} @code{defcallback} will not work correctly
6515 on some Lisps if it's not a top-level form.
6517 @subheading Examples
6520 (defcfun "qsort" :void
6524 (fun-compar :pointer))
6526 (defcallback < :int ((a :pointer) (b :pointer))
6527 (let ((x (mem-ref a :int))
6528 (y (mem-ref b :int)))
6533 CFFI> (with-foreign-object (array :int 10)
6534 ;; @lispcmt{Initialize array.}
6535 (loop for i from 0 and n in '(7 2 10 4 3 5 1 6 9 8)
6536 do (setf (mem-aref array :int i) n))
6537 ;; @lispcmt{Sort it.}
6538 (qsort array 10 (foreign-type-size :int) (callback <))
6539 ;; @lispcmt{Return it as a list.}
6540 (loop for i from 0 below 10
6541 collect (mem-aref array :int i)))
6542 @result{} (1 2 3 4 5 6 7 8 9 10)
6545 @subheading See Also
6546 @seealso{callback} @*
6547 @seealso{get-callback}
6550 @c ===================================================================
6554 @node get-callback, , defcallback, Callbacks
6555 @heading get-callback
6557 @Accessor{get-callback symbol @res{} pointer}
6559 @subheading Arguments and Values
6563 A symbol denoting a callback.
6569 @subheading Description
6570 This is the functional version of the @code{callback} macro. It
6571 returns a pointer to the callback named by @var{symbol} suitable, for
6572 example, to pass as arguments to foreign functions.
6574 @subheading Examples
6577 CFFI> (defcallback sum :int ((a :int) (b :int))
6580 CFFI> (get-callback 'sum)
6581 @result{} #<A Mac Pointer #x102350>
6584 @subheading See Also
6585 @seealso{callback} @*
6586 @seealso{defcallback}
6589 @c ===================================================================
6590 @c CHAPTER: The Groveller
6592 @node The Groveller, Limitations, Callbacks, Top
6593 @chapter The Groveller
6595 @cffi{}-Grovel is a tool which makes it easier to write @cffi{}
6596 declarations for libraries that are implemented in C. That is, it
6597 grovels through the system headers, getting information about types
6598 and structures, so you don't have to. This is especially important
6599 for libraries which are implemented in different ways by different
6600 vendors, such as the @sc{unix}/@sc{posix} functions. The @cffi{}
6601 declarations are usually quite different from platform to platform,
6602 but the information you give to @cffi{}-Grovel is the same. Hence,
6603 much less work is required!
6605 If you use @acronym{ASDF}, @cffi{}-Grovel is integrated, so that it
6606 will run automatically when your system is building. This feature was
6607 inspired by SB-Grovel, a similar @acronym{SBCL}-specific project.
6608 @cffi{}-Grovel can also be used without @acronym{ASDF}.
6610 @section Building FFIs with CFFI-Grovel
6612 @cffi{}-Grovel uses a specification file (*.lisp) describing the
6613 features that need groveling. The C compiler is used to retrieve this
6614 data and write a Lisp file (*.cffi.lisp) which contains the necessary
6615 @cffi{} definitions to access the variables, structures, constants, and
6616 enums mentioned in the specification.
6618 @c This is most similar to the SB-Grovel package, upon which it is
6619 @c based. Unlike SB-Grovel, we do not currently support defining
6620 @c regular foreign functions in the specification file; those are best
6621 @c defined in normal Lisp code.
6623 @cffi{}-Grovel provides an @acronym{ASDF} component for handling the
6624 necessary calls to the C compiler and resulting file management.
6626 @c See the included CFFI-Unix package for an example of how to
6627 @c integrate a specification file with ASDF-built packages.
6630 * Groveller Syntax:: How grovel files should look like.
6631 * Groveller ASDF Integration:: ASDF components for grovel files.
6632 * Groveller Implementation Notes:: Implementation notes.
6633 * Wrapper for Inline/Static Functions and Macros:: Wrapper
6636 @node Groveller Syntax, Groveller ASDF Integration, The Groveller, The Groveller
6637 @section Specification File Syntax
6639 The specification files are read by the normal Lisp reader, so they
6640 have syntax very similar to normal Lisp code. In particular,
6641 semicolon-comments and reader-macros will work as expected.
6643 There are several forms recognized by @cffi{}-Grovel:
6645 @deffn {Grovel Form} progn &rest forms
6647 Processes a list of forms. Useful for conditionalizing several
6654 (constant (ev-enable "EV_ENABLE"))
6655 (constant (ev-disable "EV_DISABLE")))
6658 @deffn {Grovel Form} include &rest files
6660 Include the specified files (specified as strings) in the generated C
6664 @deffn {Grovel Form} in-package symbol
6666 Set the package to be used for the final Lisp output.
6669 @deffn {Grovel Form} ctype lisp-name size-designator
6671 Define a @cffi{} foreign type for the string in @var{size-designator},
6672 e.g. @code{(ctype :pid "pid_t")}.
6675 @deffn {Grovel Form} constant (lisp-name &rest c-names) &key type documentation optional
6677 Search for the constant named by the first @var{c-name} string found
6678 to be known to the C preprocessor and define it as @var{lisp-name}.
6680 The @var{type} keyword argument specifies how to grovel the constant:
6681 either @code{integer} (the default) or @code{double-float}. If
6682 @var{optional} is true, no error will be raised if all the
6683 @var{c-names} are unknown. If @var{lisp-name} is a keyword, the actual
6684 constant will be a symbol of the same name interned in the current
6688 @deffn {Grovel Form} feature lisp-feature-name c-name &key feature-list
6690 Adds @var{lisp-feature-name} to the list @var{feature-list} if the @var{c-name}
6691 string is known to the C preprocessor. @var{feature-list} defaults
6692 to @code{cl:*features*}.
6695 @deffn {Grovel Form} define name &optional value
6697 Defines an additional C preprocessor symbol, which is useful for
6698 altering the behavior of included system headers.
6701 @deffn {Grovel Form} cc-flags &rest flags
6703 Adds @var{cc-flags} to the command line arguments used for the C compiler
6707 @deffn {Grovel Form} pkg-config-cflags pkg &key optional
6709 Adds @var{pkg} to the command line arguments for the external program
6710 @code{pkg-config} and runs it to retrieve the relevant include flags
6711 used for the C compiler invocation. This syntax can be used instead of
6712 hard-coding paths using @code{cc-flags}, and ensures that include
6713 flags are added correctly on the build system. Assumes
6714 @code{pkg-config} is installed and working. @var{pkg} is a string
6715 that identifies an installed @code{pkg-config} package. See the
6716 pkg-config manual for more information. If @var{optional} is true,
6717 failure to execute @code{pkg-config} does @emph{not} abort
6721 @deffn {Grovel Form} cstruct lisp-name c-name slots
6723 Define a @cffi{} foreign struct with the slot data specfied. Slots
6724 are of the form @code{(lisp-name c-name &key type count (signed t))}.
6727 @deffn {Grovel Form} cunion lisp-name c-name slots
6729 Identical to @code{cstruct}, but defines a @cffi{} foreign union.
6732 @deffn {Grovel Form} cstruct-and-class c-name slots
6734 Defines a @cffi{} foreign struct, as with @code{cstruct} and defines a
6735 @acronym{CLOS} class to be used with it. This is useful for mapping
6736 foreign structures to application-layer code that shouldn't need to
6737 worry about memory allocation issues.
6740 @deffn {Grovel Form} cvar namespec type &key read-only
6742 Defines a foreign variable of the specified type, even if that
6743 variable is potentially a C preprocessor pseudo-variable. e.g.
6744 @code{(cvar ("errno" errno) errno-values)}, assuming that errno-values
6745 is an enum or equivalent to type @code{:int}.
6747 The @var{namespec} is similar to the one used in @ref{defcvar}.
6750 @deffn {Grovel Form} cenum name-and-opts &rest elements
6752 Defines a true C enum, with elements specified as @code{((lisp-name
6753 &rest c-names) &key optional documentation)}.
6754 @var{name-and-opts} can be either a symbol as name, or a list
6755 @code{(name &key base-type define-constants)}. If @var{define-constants}
6756 is non-null, a Lisp constant will be defined for each enum member.
6759 @deffn {Grovel Form} constantenum name-and-opts &rest elements
6761 Defines an enumeration of pre-processor constants, with elements
6762 specified as @code{((lisp-name &rest c-names) &key optional
6764 @var{name-and-opts} can be either a symbol as name, or a list
6765 @code{(name &key base-type define-constants)}. If @var{define-constants}
6766 is non-null, a Lisp constant will be defined for each enum member.
6768 This example defines @code{:af-inet} to represent the value held by
6769 @code{AF_INET} or @code{PF_INET}, whichever the pre-processor finds
6770 first. Similarly for @code{:af-packet}, but no error will be
6771 signalled if the platform supports neither @code{AF_PACKET} nor
6776 (constantenum address-family
6777 ((:af-inet "AF_INET" "PF_INET")
6778 :documentation "IPv4 Protocol family")
6779 ((:af-local "AF_UNIX" "AF_LOCAL" "PF_UNIX" "PF_LOCAL")
6780 :documentation "File domain sockets")
6781 ((:af-inet6 "AF_INET6" "PF_INET6")
6782 :documentation "IPv6 Protocol family")
6783 ((:af-packet "AF_PACKET" "PF_PACKET")
6784 :documentation "Raw packet access"
6788 @deffn {Grovel Form} bitfield name-and-opts &rest elements
6790 Defines a bitfield, with elements specified as @code{((lisp-name &rest
6791 c-names) &key optional documentation)}. @var{name-and-opts} can be either a
6792 symbol as name, or a list @code{(name &key base-type)}. For example:
6796 (bitfield flags-ctype
6798 :documentation "DOCU_A")
6799 ((:flag-b "FLAG_B" "FLAG_B_ALT")
6800 :documentation "DOCU_B")
6802 :documentation "DOCU_C"
6807 @c ===================================================================
6808 @c SECTION: Groveller ASDF Integration
6810 @node Groveller ASDF Integration, Groveller Implementation Notes, Groveller Syntax, The Groveller
6811 @section ASDF Integration
6813 An example software project might contain four files; an
6814 @acronym{ASDF} file, a package definition file, an implementation
6815 file, and a @cffi{}-Grovel specification file.
6817 The @acronym{ASDF} file defines the system and its dependencies.
6818 Notice the use of @code{eval-when} to ensure @cffi{}-Grovel is present
6819 and the use of @code{(cffi-grovel:grovel-file name &key cc-flags)}
6820 instead of @code{(:file name)}.
6822 The @file{example-software.asd} file would look like that:
6825 ;;; @lispcmt{CFFI-Grovel is needed for processing grovel-file components}
6826 (defsystem "example-software"
6827 :defsystem-depends-on ("cffi-grovel")
6828 :depends-on ("cffi")
6832 (:cffi-grovel-file "example-grovelling")
6833 (:cffi-wrapper-file "example-wrappers")
6837 The @file{package.lisp} file would contain one or several
6838 @code{defpackage} forms, to remove circular dependencies and make
6839 building the project easier. Note that you may or may not want to
6840 @code{:use} your internal package.
6842 @impnote{Note that it's a not a good idea to @code{:use} when names may
6843 clash with, say, CL symbols.
6844 Or you could use @code{uiop:define-package} and its @code{:mix} option.}
6847 (defpackage #:example-internal
6849 (:nicknames #:exampleint))
6851 (defpackage #:example-software
6853 (:use #:cl #:cffi #:exampleint))
6856 The internal package is created by Lisp code output from the C program
6857 written by @cffi{}-Grovel; if your specification file is
6858 @file{exampleint.lisp}, the @file{exampleint.cffi.lisp} file will contain the
6859 @cffi{} definitions needed by the rest of your project.
6860 @xref{Groveller Syntax}.
6862 @node Groveller Implementation Notes, Wrapper for Inline/Static Functions and Macros, Groveller ASDF Integration, The Groveller
6863 @section Implementation Notes
6865 @cffi{}-Grovel will generate many files that not only architecture-specific,
6866 but also implementation-specific, and should not be distributed.
6867 ASDF will generate these files in its output cache;
6868 if you build with multiple architectures (e.g. with NFS/AFS home
6869 directories) or implementations, it is critical for avoiding clashes
6870 to keep this cache in an implementation-dependent directory (as is the
6873 For @code{foo-internal.lisp}, the resulting @code{foo-internal.c},
6874 @code{foo-internal}, and @code{foo-internal.cffi.lisp} are all
6875 platform-specific, either because of possible reader-macros in
6876 foo-internal.lisp, or because of varying C environments on the host
6877 system. For this reason, it is not helpful to distribute any of those
6878 files; end users building @cffi{}-Grovel based software will need
6879 @code{cffi}-Grovel anyway.
6881 @impnote{For now, after some experimentation with @sc{clisp} having no
6882 long-long, it seems appropriate to assert that the generated @code{.c}
6883 files are architecture and operating-system dependent, but
6884 lisp-implementation independent. This way the same @code{.c} file
6885 (and so the same @code{.grovel-tmp.lisp} file) will be shareable
6886 between the implementations running on a given system.}
6888 @c TODO: document the new wrapper stuff.
6890 @node Wrapper for Inline/Static Functions and Macros, , Groveller Implementation Notes, The Groveller
6891 @section Wrapper for Inline/Static Functions and Macros
6893 In a shared library, information in static/inlined functions and
6894 macros are already removed during the compilation. Wrapper file
6895 enables to write an uninlined function wrapping the call to them.
6897 A wrapper file compilation/loading proceeds as follows:
6898 Unlike groveller which generates C code that emits lisp files
6899 containing cffi definitions, it generates C code, compiles it as a
6900 shared library, loads the library, generate the cffi definitions (as
6901 lisp code) and then loads the lisp code.
6903 It has asdf integration similar to groveller.
6906 (defsystem "example-software"
6907 :defsystem-depends-on ("cffi-grovel")
6908 :depends-on ("cffi")
6912 (:cffi-grovel-file "example-grovelling")
6913 (:cffi-wrapper-file "example-wrappers") ;; <<--- this part
6917 @deffn {Wrapper Form} defwrapper name-and-options return-type &rest args
6921 static inline int foo(int i) @{
6924 #define bar(i) (1+(i))
6928 (in-package :mypackage)
6929 (defwrapper ("foo" foo) :int
6931 (defwrapper ("bar" bar) :int
6935 Other forms are similar to grovel files.
6937 @deffn {Wrapper Form} progn &rest forms
6939 Processes a list of forms. Useful for conditionalizing several
6946 (constant (ev-enable "EV_ENABLE"))
6947 (constant (ev-disable "EV_DISABLE")))
6950 @deffn {Wrapper Form} include &rest files
6952 Include the specified files (specified as strings) in the generated C
6956 @deffn {Wrapper Form} in-package symbol
6958 Set the package to be used for the final Lisp output.
6961 @deffn {Wrapper Form} flags &rest flags
6963 Adds @var{cc-flags} to the command line arguments used for the C compiler
6967 @deffn {Wrapper Form} proclaim &rest proclaimations
6969 @deffn {Wrapper Form} declaim &rest declaimations
6974 @c ===================================================================
6975 @c CHAPTER: Static Linking
6977 @node Static Linking, Limitations, The Groveller, Top
6978 @chapter Static Linking
6980 On recent enough versions of supported implementations (currently,
6981 GNU CLISP 2.49, CMUCL 2015-11, and SBCL 1.2.17), and with a recent
6982 enough ASDF (3.1.2 or later), you can create a statically linked
6983 Lisp executable image that includes all the C extensions
6984 (wrappers and any other objects output by @code{compile-op})
6985 as well as your Lisp code --- or a standalone application executable.
6986 This makes it easier to deliver your code as a single file.
6988 To dump a statically linked executable image, use:
6991 (asdf:load-system :cffi-grovel)
6992 (asdf:operate :static-image-op :example-software)
6995 To dump a statically linked executable standalone application, use:
6998 (asdf:load-system :cffi-grovel)
6999 (asdf:operate :static-program-op :example-software)
7002 See @uref{https://common-lisp.net/project/asdf/,,the ASDF
7003 manual} for documentation about @code{image-op} and @code{program-op}
7004 which are the parent operation classes that behave similarly except
7005 they don't statically link C code.
7007 @impnote{There is also an operation @code{:static-runtime-op} to create the
7008 statically linked runtime alone, but it's admittedly not very useful
7009 except as an intermediate step dependency towards building
7010 @code{:static-image-op} or @code{:static-program-op}.}
7014 @c ===================================================================
7015 @c CHAPTER: Limitations
7017 @node Limitations, Platform-specific features, The Groveller, Top
7018 @chapter Limitations
7020 These are @cffi{}'s limitations across all platforms; for information
7021 on the warts on particular Lisp implementations, see
7022 @ref{Implementation Support}.
7026 The tutorial includes a treatment of the primary, intractable
7027 limitation of @cffi{}, or any @acronym{FFI}: that the abstractions
7028 commonly used by C are insufficiently expressive.
7029 @xref{Tutorial-Abstraction,, Breaking the abstraction}, for more
7035 @node Platform-specific features, Glossary, Limitations, Top
7036 @appendix Platform-specific features
7038 Whenever a backend doesn't support one of @cffi{}'s features, a
7039 specific symbol is pushed onto @code{common-lisp:*features*}. The
7040 meanings of these symbols follow.
7043 @item cffi-sys::flat-namespace
7044 This Lisp has a flat namespace for foreign symbols meaning that you
7045 won't be able to load two different libraries with homograph functions
7046 and successfully differentiate them through the @code{:library}
7047 option to @code{defcfun}, @code{defcvar}, etc@dots{}
7049 @item cffi-sys::no-foreign-funcall
7050 The macro @code{foreign-funcall} is @strong{not} available. On such
7051 platforms, the only way to call a foreign function is through
7052 @code{defcfun}. @xref{foreign-funcall}, and @ref{defcfun}.
7054 @item cffi-sys::no-long-long
7055 The C @code{long long} type is @strong{not} available as a foreign
7058 However, on such platforms @cffi{} provides its own implementation of
7059 the @code{long long} type for all of operations in chapters
7060 @ref{Foreign Types}, @ref{Pointers} and @ref{Variables}. The
7061 functionality described in @ref{Functions} and @ref{Callbacks} will
7064 32-bit Lispworks 5.0+ is an exception. In addition to the @cffi{}
7065 implementation described above, Lispworks itself implements the
7066 @code{long long} type for @ref{Functions}. @ref{Callbacks} are still
7067 missing @code{long long} support, though.
7069 @item cffi-sys::no-stdcall
7070 This Lisp doesn't support the @code{stdcall} calling convention. Note
7071 that it only makes sense to support @code{stdcall} on (32-bit) x86
7077 @node Glossary, Comprehensive Index, Platform-specific features, Top
7081 @item aggregate type
7082 A @cffi{} type for C data defined as an organization of data of simple
7083 type; in structures and unions, which are themselves aggregate types,
7084 they are represented by value.
7087 This has two meanings; in any context, only one makes sense.
7089 When using type translators, the foreign value is the lower-level Lisp
7090 value derived from the object passed to @code{translate-to-foreign}
7091 (@pxref{translate-to-foreign}). This value should be a Lisp number or
7092 a pointer (satisfies @code{pointerp}), and it can be treated like any
7093 general Lisp object; it only completes the transformation to a true
7094 foreign value when passed through low-level code in the Lisp
7095 implementation, such as the foreign function caller or indirect memory
7096 addressing combined with a data move.
7098 In other contexts, this refers to a value accessible by C, but which
7099 may only be accessed through @cffi{} functions. The closest you can
7100 get to such a foreign value is through a pointer Lisp object, which
7101 itself counts as a foreign value in only the previous sense.
7104 A @cffi{} type that is ultimately represented as a builtin type;
7105 @cffi{} only provides extra semantics for Lisp that are invisible to C
7109 @node Comprehensive Index, , Glossary, Top