[cffi-devel] loading foreign libraries in a top-level form

Frank Goenninger frgo at me.com
Mon Oct 22 05:26:19 UTC 2012


Hi Anton,

Am 22.10.2012 um 05:28 schrieb Anton Vodonosov <avodonosov at yandex.ru>:

> Hello.
> 
> The CFFI manual says [1] that cffi:use-foreign-library is intended to be the
> top-level form used idiomatically to go ahead and load the library.
> 
> And most developers follow this idiom.

What makes you think so? I don't.

> 
> I would argue that this is inconvenient.

That's what led me to follow a simple two-step idiom:

(in-package :de.consequor.app.core)

;;; -------------------------------------------------------------------
;;; C LIB FFI Definition
;;; -------------------------------------------------------------------

(eval-now!
 (define-foreign-library CCAGCORE_LIB
     (t (:default "libccagcore"))))

(defparameter *CCAGCORE-DEFAULT-LIBDIR* "Z:/var/data/consequor/swdev/ccagcore/lib/")
(defparameter *CCAGCORE-LIBDIR* nil)

(defun set-ccagcore-libdir (&optional (libdir *CCAGCORE-DEFAULT-LIBDIR*))
  (setq *CCAGCORE-LIBDIR* libdir))

(defun ensure-ccagcore-libdir-set ()
  (unless *CCAGCORE-LIBDIR*
    (setq *CCAGCORE-LIBDIR* *CCAGCORE-DEFAULT-LIBDIR*)))

(defun push-ccagcore-libdir ()
  (pushnew *CCAGCORE-LIBDIR* cffi:*foreign-library-directories* :test #'string=))

(let ((loaded nil))

  (defun load-ccagcore-lib ()
    (unless loaded
      (ensure-ccagcore-libdir-set)
      (push-ccagcore-libdir)
      (load-foreign-library 'CCAGCORE_LIB)
      (setq loaded t)
      (ccag-log :INFO "LOAD-CCAGCORE-LIB" 0 "CCAGCORE LIB loaded." )))

  (defun unload-ccagcore-lib ()
    (when loaded
      (close-foreign-library 'CCAGCORE_LIB)
      (setq loaded nil)
      (ccag-log :INFO "UNLOAD-CCAGCORE-LIB" 0 "CCAGCORE LIB unloaded." )))

  (defun ensure-ccagcore-lib-loaded ()
    (unless loaded
      (load-ccagcore-lib)))
  )


Simple. Works. No problems on any platform.

Cheers
    Frank





More information about the cffi-devel mailing list