[cffi-devel] Re: CFFI malloc free

Luís Oliveira luismbo at gmail.com
Mon Dec 19 07:15:38 UTC 2005


Surendra Singhi <efuzzyone at netscape.net> writes:
>  If I have a C function which allocates memory for a C string and returns a
> pointer to this memory (return type char *).
>
> Should the return type of this function be :string or :pointer? 

Either :pointer or :string+ptr. The :string+ptr type will return a list
with two values: a lisp string and a pointer to the C string.


> How do I deallocate this memory? Should I use `foreign-string-free' or
> `foreign-free'. 

I have been meaning to look into this. Right now, you'd have to use
something like (foreign-funcall "free" :pointer <your-pointer>)


> Is there any way this deallocation can be made automatic?

Not that I know of. However, I suspect that, in your case, something like
this would suffice:

(defcfun your-foreign-function :pointer ...)

(defun your-wrapper-around-the-foreign-function (...)
  (let ((ptr (your-foreign-function ...)))
    (unwind-protect
        (foreign-string-to-lisp ptr)
      (foreign-funcall "free" :pointer ptr))))


Or you could define a new type to do this:

(defctype my-string :pointer)

(define-type-translator my-string :from-c (value)
  "Converts a foreign string to lisp, and frees it."
  (once-only (value)
    `(unwind-protect (foreign-string-to-lisp ,value)
       (foreign-funcall "free" :pointer ptr))))

(defcfun your-foreign-function my-string ...)

-- 
Luís Oliveira
luismbo (@) gmail (.) com
Equipa Portuguesa do Translation Project
http://www.iro.umontreal.ca/translation/registry.cgi?team=pt




More information about the cffi-devel mailing list