[racket] Freeing FFI resources

From: Eli Barzilay (eli at barzilay.org)
Date: Mon Oct 11 20:24:37 EDT 2010

20 minutes ago, Neil Toronto wrote:
> Eli Barzilay wrote:
> > 5 hours ago, Neil Toronto wrote:
> >> I'd be wary of the bytes/free example: I'd free the bytes ASAP
> >> instead of using a finalizer.
> > 
> > That shouldn't be a problem.
> Not for correctness, no. How about for time or memory efficiency?

Neither for that.

But of course if the problem is the original one in this thread, where
each C string eventually needs to be converted to a Racket string,
then there's little point in holding on to a pointer instead of
converting it immediately (and freeing the C pointer).

> My structs were a smidge more complicated, and Racket bloated in
> memory when I used them. Hence my general preference for
> copy-and-free over registering a finalizer.

With this code:

  #lang racket
  (require ffi/unsafe)
  (define bytes/free
    (make-ctype _bytes
                #f ; a Racket bytes can be used as a pointer
                (lambda (b)
                  (register-finalizer b free)
  (define strdup
    (get-ffi-obj 'strdup #f (_fun _bytes -> bytes/free)))
  (for ([i (in-range 1000000000)]) (strdup #"bleh"))

I get memory at around 200mb; with a `free' instead of the finalizer,
it's around 130mb.

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                    http://barzilay.org/                   Maze is Life!

Posted on the users mailing list.