[racket] Freeing FFI resources

From: Jon Zeppieri (zeppieri at gmail.com)
Date: Mon Oct 11 15:02:58 EDT 2010

On Mon, Oct 11, 2010 at 2:02 PM, Neil Toronto <neil.toronto at gmail.com> wrote:
> Eric Dobson wrote:
>>
>> I am dealing with a foreign library that has functions that return
>> error messages in a char** input argument. These need to be explicitly
>> freed by calling another function. I figured out how to get them into
>> racket strings by using the _ptr and the _string ctype. But I didn't
>> see a way to capture the value before conversion to a racket string so
>> that I could free the original string, and continue to use the _string
>> conversion process. Is there an easy way to do these two thing
>> together?
>
> You can pass a bytes object to foreign code that expects a char*, and it'll
> be passed as a pointer to the byte data. So use _bytes instead of _string,
> call (probably) bytes->string/utf-8, and then pass the bytes object to the
> foreign function that frees them.

So my _out-string definition could be simplified to:

(define _out-string
  (make-ctype _bytes
              #f
              (λ (x)
                (let ((s (bytes->string/latin-1 x))) ;; or /utf-8,
depending on your C lib
                  (free-err-msg x)
                  s))))

I wasn't sure how this would interact with the GC, but it appears to work.


>
> I'd be wary of the bytes/free example: I'd free the bytes ASAP instead of
> using a finalizer.

Yeah, that was my thought, too.


Posted on the users mailing list.