How does CFFI handle returned string?

Discussion of Common Lisp
Post Reply
wvxvw
Posts: 127
Joined: Sat Mar 26, 2011 6:23 am

How does CFFI handle returned string?

Post by wvxvw » Sat Sep 13, 2014 11:26 am

Imagine I have this function:

Code: Select all

(cffi:defcfun ("linkage_print_diagram" linkage_print_diagram) :string
  (linkage :pointer)
  (display_walls :boolean)
  (screen_width :int))
Which wraps a function which returns an allocated memory, which it requests the callers of this function to free. Should I:

- return a :pointer rather than :string and free the memory pointed by the pointer when it's not needed, or
- do nothing, CFFI already did it. I.e. the meaning of returning a :string is that it was copied into Lisp string, and the original was deallocated.?

logxor
Posts: 20
Joined: Tue May 27, 2014 10:56 am
Location: Portland, OR

Re: How does CFFI handle returned string?

Post by logxor » Sun Sep 14, 2014 3:55 pm

I don't have CFFI handy to try this out, but it appears that the :STRING type takes a :FREE-FROM-FOREIGN option that specifies whether to free the foreign string after it's been translated to a Lisp string. The default is NIL, so:

Code: Select all

(cffi:defcfun ("linkage_print_diagram" linkage_print_diagram)
    (:string :free-from-foreign t)
  (linkage :pointer)
  (display_walls :boolean)
  (screen_width :int))

wvxvw
Posts: 127
Joined: Sat Mar 26, 2011 6:23 am

Re: How does CFFI handle returned string?

Post by wvxvw » Mon Sep 15, 2014 11:28 am

Oh, that's great. Even better, than I expected! Thanks.

Post Reply