Luís Oliveira <[EMAIL PROTECTED]> writes: > Surendra Singhi <[EMAIL PROTECTED]> 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)))) >
Can the foreign string in the above example contain the null character? Or does cffi assumes that it is a null terminated string? Thanks. -- Surendra Singhi http://www.public.asu.edu/~sksinghi/index.html ,---- | WHY SHOULD WE SAVE TIGER? | Ans: Saving the tiger means saving mankind.. | | Help http://pudang.tripod.com/ | or https://secure.worldwildlife.org/forms/tiger_appeal_1.cfm `---- _______________________________________________ cffi-devel mailing list cffi-devel@common-lisp.net http://common-lisp.net/cgi-bin/mailman/listinfo/cffi-devel