Name

ext:set-finalizer — Associate a finalizer to an object.

Function

(ext:set-finalizer object function)

object

Any lisp object.

function

A function or closure that takes one argument or NIL.

Description

If function is NIL no finalizer is associated to the object. Otherwise function must be a function or a closure of one argument, which will be invoked before the object is destroyed.

Example

Close a file associated to an object.

(defclass my-class () ((file :initarg :file :initform nil)))

(defun finalize-my-class (x)
 (let ((s (slot-value x 'file)))
   (when s (format t "~%;;; Closing" s) (close s))))

(defmethod initialize-instance :around ((my-instance my-class) &rest args)
  (ext:set-finalizer my-instance #'finalize-my-class)
  (call-next-method))

(progn
  (make-instance 'my-class :file (open "~/.ecl.old" :direction :input))
  nil)

(si::gc t)
(si::gc t)

;; Closing