&uffi; has functions to two types of
<varname>C</varname>-compatible
- strings, <emphasis>cstring</emphasis> and <emphasis>foreign</emphasis> 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
-<emphasis>allocate</emphasis> a cstring.
+ strings: <emphasis>cstring</emphasis> and
+<emphasis>foreign</emphasis> strings.
+
+cstrings are used <emphasis>only</emphasis> 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.
</para>
-<para>
-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.
- </para>
+
+<programlisting>
+(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))))
+</programlisting>
+
+<para> 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. </para>
+
+<programlisting>
+(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."))))
+</programlisting>
+
</partintro>
<refentry id="convert-from-cstring">
<title>Description</title>
<para>
Frees any memory possibly allocated by
- <function>convert-to-cstring</function>.
+ <function>convert-to-cstring</function>. On some implementions, a cstring is just the Lisp string itself.
</para>
</refsect1>
<refsect1>