The Foreign Function Interface
Binding generators: cl-autowrap / claw (from C headers via c2ffi), the cffi-grovel ASDF extension (constants and struct layouts). Other interop: py4cl2 (Python), ABCL (Java), Clasp (C++), ECL (embedding in C).
(ql:quickload "cffi")
;; Call C standard library functions
(cffi:defcfun "strlen" :size (s :string))
(strlen "Common Lisp") ; 11
(cffi:defcfun ("abs" c-abs) :int (n :int)) ; rename the Lisp-side function
(c-abs -5) ; 5
;; Load a shared library
(cffi:define-foreign-library libm
(:darwin "libm.dylib")
(:unix (:or "libm.so.6" "libm.so"))
(t (:default "libm")))
(cffi:use-foreign-library libm)
(cffi:defcfun "cbrt" :double (x :double))
(cbrt 27d0) ; 3.0d0
;; Structs and memory
(cffi:defcstruct point
(x :int)
(y :int))
(cffi:with-foreign-object (p '(:struct point))
(setf (cffi:foreign-slot-value p '(:struct point) 'x) 10
(cffi:foreign-slot-value p '(:struct point) 'y) 20)
(+ (cffi:foreign-slot-value p '(:struct point) 'x)
(cffi:foreign-slot-value p '(:struct point) 'y))) ; 30
(cffi:with-foreign-string (s "hello")
(cffi:foreign-string-to-lisp s)) ; "hello"
(let ((buf (cffi:foreign-alloc :double :count 3 :initial-contents '(1d0 2d0 3d0))))
(unwind-protect (cffi:mem-aref buf :double 1) ; 2.0d0
(cffi:foreign-free buf)))
;; Callbacks: Lisp functions callable from C
(
…