X-Git-Url: http://git.kpe.io/?a=blobdiff_plain;f=doc%2Fref.sgml;h=f299c197cee87f90e5045c6c1ddca6b4d89198c1;hb=0fd4491dbbe35c43abecd56549d8efd59760c73d;hp=39ae02ebaf9a920fceb1b76cef1a1671bd0f70fb;hpb=005eb1c1210634a27fbc973d84004b5622456fc5;p=uffi.git diff --git a/doc/ref.sgml b/doc/ref.sgml index 39ae02e..f299c19 100644 --- a/doc/ref.sgml +++ b/doc/ref.sgml @@ -1498,21 +1498,51 @@ if a cstring returned by a function is &null;. &uffi; has functions to two types of C-compatible - strings, cstring and foreign strings. - -cstrings are used as parameters to and from functions. An -implementation, such as CMUCL and Lispworks, a cstring may not be a -foreign type but rather the Lisp string itself while on other -platforms a cstring is a newly allocated foreign vector for storing -characters. Thus, it is not possible to portably -allocate a cstring. + strings: cstring and +foreign strings. + +cstrings are used only as parameters to and from +functions. In some implementations a cstring is not a foreign type but +rather the Lisp string itself. On other platforms a cstring is a newly +allocated foreign vector for storing characters. The following is an +example of using cstrings to both send and return a value. - -In contrast, foreign strings -are always a foreign vector of characters which have a memory -allocated to hold them. Because of this, if you need to allocate memory to -hold the return value of a string, use a foreign string and not a cstring. - + + +(uffi:def-function ("getenv" c-getenv) + ((name :cstring)) + :returning :cstring) + +(defun my-getenv (key) + "Returns an environment variable, or NIL if it does not exist" + (check-type key string) + (uffi:with-cstring (key-native key) + (uffi:convert-from-cstring (c-getenv key-native)))) + + + In contrast, foreign strings are always a foreign vector of +characters which have memory allocated. Thus, if you need to allocate +memory to hold the return value of a string, you must use a foreign +string and not a cstring. The following is an example of using a foreign +string for a return value. + + +(uffi:def-function ("gethostname" c-gethostname) + ((name (* :unsigned-char)) + (len :int)) + :returning :int) + +(defun gethostname () + "Returns the hostname" + (let* ((name (uffi:allocate-foreign-string 256)) + (result-code (c-gethostname name 256)) + (hostname (when (zerop result-code) + (uffi:convert-from-foreign-string name)))) + (uffi:free-foreign-object name) + (unless (zerop result-code) + (error "gethostname() failed.")))) + + @@ -1655,7 +1685,7 @@ that returns a cstring. Description Frees any memory possibly allocated by - convert-to-cstring. + convert-to-cstring. On some implementions, a cstring is just the Lisp string itself.