This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

How does CFFI handle returned string?

3 posts · 3096 views

Imagine I have this function:
(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.?

Re: How does CFFI handle returned string?

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:
(cffi:defcfun ("linkage_print_diagram" linkage_print_diagram)
    (:string :free-from-foreign t)
  (linkage :pointer)
  (display_walls :boolean)
  (screen_width :int))

Re: How does CFFI handle returned string?

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