[cffi-devel] A question about memory management and garbage collection

Martin Simmons martin at lispworks.com
Mon May 9 11:49:51 UTC 2011


>>>>> On Sun, 08 May 2011 14:39:41 +0200, Nitralime  said:
> 
> Using a finalizer seems to be a possible way to go. But I'm not sure how
> this can be done by just using the finalizer parameters "object" and 
> "function"
> where "function" can't reliablely access "object" (cf. documentation of 
> finalizer
> in "trivial-garbage"  package)!!
> 
> Any help and feedback is very much appreciated!

IMHO, attempting to transparently wrap a foreign object with a CLOS object is
not a good design.

Using a finalizer is dangerous because it is difficult to guarantee that the
Lisp wrapper object is retained for the correct lifetime.

For example, consider

(defstruct table
  foreign-pointer)

(defun allocate-table ()
  (make-table :foreign-pointer (foreign-allocate-table)))

(defun allocate-and-munge-table ()
  (let ((table (allocate-table)))
    (foreign-munge-table (table-foreign-pointer table))))

The compiler might not keep the variable "table" alive during the call to the
foreign function foreign-munge-table.  As a result, the Lisp table object
might be gc'ed in another thread while the foreign code is accessing it.

-- 
Martin Simmons
LispWorks Ltd
http://www.lispworks.com/




More information about the cffi-devel mailing list