This example builds a dynamic library which in principle could be loaded by any application and called to calculate square numbers.
For illustrative purposes, we show how to load the dynamic library into the LispWorks development image. This illustrates some platform-specific initialization. Then we use the library, ensure it exits cleanly, and finally delete the dynamic library file.
Note that on Linux/Macintosh/FreeBSD, to deliver a dynamic library, the build machine must have a C compiler installed.
For convenience the code is presented without external files. To run it, copy each form in turn and enter it at the Listener prompt.
(merge-pathnames (make-pathname :name "CalculateSquareExample"
(defun save-dynamic-library ()
(let* ((file (open-temp-file :file-type "lisp"))
(ns (namestring file)))
(fli:define-foreign-callable (calculate-square :result-type :int)
(* arg arg))
(deliver nil ~s 5 :dll-exports '(\"calculate_square\"))"
(sys:call-system-showing-output (list (lisp-image-name)
(delete-file file nil)))
(fli:define-foreign-function (my-quit-lispworks "QuitLispWorks")
;; specifying :module ensures the foreign function finds
;; the function in our module
(fli:define-foreign-function (my-init-lispworks "InitLispWorks")
(base-address (:pointer-integer :int))
(reserve-size (:pointer-integer :int)) ; really size_t
(defun run-the-dynamic-library ()
;; Windows and Mac OS X can detect and resolve memory clashes.
;; On other platforms, tell the library to load at different
;; address (that is, relocate) because otherwise it will use
;; the same address as the running LispWorks development image.
;; Relocation may be needed when loading a LispWorks dynamic
;; library in other applications.
#-(or mswindows darwin)
(dotimes (x 4)
(format t "square of ~d = ~d~%" x
(my-quit-lispworks 0 1000)
Check the output to see that it computed square numbers.
(delete-file *dynamic-library-path* nil)
LispWorks Delivery User Guide - 13 Dec 2011