[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: dynamic-ffi: Responsibility for freeing returned pointers?
From: |
Ludovic Courtès |
Subject: |
Re: dynamic-ffi: Responsibility for freeing returned pointers? |
Date: |
Mon, 13 Nov 2017 14:51:39 +0100 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/25.3 (gnu/linux) |
Hi Tom,
Tom Jakubowski <address@hidden> skribis:
> Say I have a C function like this:
>
> char *tom_hello() {
> return strdup("hello!");
> }
>
> And, in Guile land, I make a procedure c-tom-hello out of it using
> dynamic-ffi and wrap it in a function that returns a Scheme string:
>
> (define exe (dynamic-link))
> (define c-tom-hello (pointer->procedure '* (dynamic-func "tom_hello" exe)
> '())
> (define (tom-hello)
> (let ((str (pointer->string c-tom-hello)))
> ;; free pointer?
> str))
>
> My assumption (supported by reading strings.c, but not in any docs I can
> find) is that pointer->string makes a copy of the string it's passed.
Indeed.
> This leaves open the question of freeing the original string returned
> by the tom_hello() C function.
It’s up to the programmer, as in C. In this case, you could add an
explicit call to ‘free’, or do:
(set-pointer-finalizer! ptr (dynamic-func "free" (dynamic-link)))
so that ‘free’ gets called eventually, when ‘ptr’ becomes unreachable.
> Is the usual technique here to use dynamic-ffi to make a procedure that's
> bound to C's free(), and call that on the C string after making the Guile
> string from it? It seems like the obvious choice, I'd just like to be sure
> I'm not missing some higher level approach I should use instead.
I think it’s the right approach.
HTH,
Ludo’.