[Cffi-devel] Fw: What is the proper way to do GC in CFFI

Willem Rein Oudshoorn woudshoo at xs4all.nl
Sun Apr 13 15:25:51 UTC 2014


Joeish W <joeish80829 at yahoo.com> writes:

> I already figured out a great finalizer, I could just use help on one thing.
> The below finalizer is for the %mat defcfun below that.
> How do I update the finalizer below to be for the mat-data defcfun at the 
> bottom of the page. So where do I put the rows cols params, there seems 
> to be no place for them in the defstruct wwhere %mat is called. Any
> help is appreciated 

Hm, I feel this is not the right way to approach this. 
However, there is a bug in your finalize logic.

1. If you call make-cvmatrix with enable-finalizer true you attach a
   finalize on the new instance of cvmatrix.  
2. However you return the SAP.  
3. As a consequence the cvmatrix instance can be immediately garbage
   collected, even if the returned SAP still has references to it.

        

> (defstruct (cvmatrix (:constructor %make-cvmatrix)) 
>   (sap (%mat) :type sb-sys:system-area-pointer :read-only t)) 
>  
>  (defun make-cvmatrix (&optional enable-finalizer) 
>   (let* ((matrix (%make-cvmatrix)) 
>           (sap (cvmatrix-sap matrix))) 
> (when enable-finalizer 
>     (tg:finalize matrix (lambda () (del-mat sap)))) 
>     sap)) 

I do not think that this is what you want.

Two remarks for future improvement:

1. You use sb-sys:system-area-pointer as type, and this will tie you to
   SBCL.   There is no reason for that.

2. You should read up on `translate-to-foreign' and
   `translate-from-foreign' in the cffi documentation.  It will really
   help to make the code simpler, cleaner and more robust.

If I have more time I might give some more detailed suggestions.  But I
hope this helps a bit.

Wim Oudshoorn.





More information about the cffi-devel mailing list