[cffi-devel] Re: CFFI malloc free

Surendra Singhi efuzzyone at netscape.net
Mon Dec 19 07:59:27 UTC 2005


Luís Oliveira <luismbo at gmail.com> writes:

> 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 ...)
>

Thanks. 

-- 
Surendra Singhi
http://www.public.asu.edu/~sksinghi/index.html

,----
| "All animals are equal, but some animals are more equal than others."
|     -- Orwell, Animal Farm, 1945
`----




More information about the cffi-devel mailing list