[cffi-devel] CLisp finalizers

Marco Gidde marco.gidde at tiscali.de
Sun Feb 4 19:19:31 UTC 2007


Hi,

as mentioned on this list CLisp has some problems with the
finalization code provided by CFFI. I guess this is due to accessing
the weak hash table within the finalizer. The following code works
around this problem by closing the "main finalizer" over the list of
the "sub finalizers".


(in-package :cffi-sys)

(defvar *finalizers* (make-hash-table :test 'eq :weak :key)
  "Weak hashtable that holds registered finalizers.")

(defun finalize (object function)
  "Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.

For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
  (multiple-value-bind (finalizers present-p)
      (gethash object *finalizers* (cons 'finalizers nil))
    (unless present-p
      (setf (gethash object *finalizers*) finalizers)
      (ext:finalize object (lambda (obj)
                             (declare (ignore obj))
			     (mapc #'funcall (cdr finalizers)))))
    (push function (cdr finalizers)))
  object)


(defun cancel-finalization (object)
  "Cancels all of OBJECT's finalizers, if any."
  (multiple-value-bind (finalizers present-p)
      (gethash object *finalizers*)
    (when present-p
      (setf (cdr finalizers) nil)))
  (remhash object *finalizers*))


While this code isn't as short and elegant as the original code, at
least it works ;-)


Regards,

Marco




More information about the cffi-devel mailing list