ftw: Add an optional `stat' parameter to `file-system-fold' and `-tree'.
[bpt/guile.git] / doc / ref / api-foreign.texi
index 1e735db..2dd6916 100644 (file)
@@ -1,10 +1,9 @@
 @c -*-texinfo-*-
 @c This is part of the GNU Guile Reference Manual.
-@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2008, 2009, 2010
-@c   Free Software Foundation, Inc.
+@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2008,
+@c   2009, 2010, 2011 Free Software Foundation, Inc.
 @c See the file guile.texi for copying conditions.
 
-@page
 @node Foreign Function Interface
 @section Foreign Function Interface
 @cindex foreign function interface
@@ -18,7 +17,7 @@ But yet we as programmers live in both worlds, and Guile itself is half
 implemented in C. So it is that Guile's living half pays respect to its
 dead counterpart, via a spectrum of interfaces to C ranging from dynamic
 loading of Scheme primitives to dynamic binding of stock C library
-prodedures.
+procedures.
 
 @menu
 * Foreign Libraries::           Dynamically linking to libraries.
@@ -80,6 +79,12 @@ Normally, @var{library} is just the name of some shared library file
 that will be searched for in the places where shared libraries usually
 reside, such as in @file{/usr/lib} and @file{/usr/local/lib}.
 
+@var{library} should not contain an extension such as @code{.so}.  The
+correct file name extension for the host operating system is provided
+automatically, according to libltdl's rules (@pxref{Libltdl interface,
+lt_dlopenext, @code{lt_dlopenext}, libtool, Shared Library Support for
+GNU}).
+
 When @var{library} is omitted, a @dfn{global symbol handle} is returned.  This
 handle provides access to the symbols available to the program at run-time,
 including those exported by the program itself and the shared libraries already
@@ -197,12 +202,13 @@ In that case, you would statically link your program with the desired
 library, and register its init function right after Guile has been
 initialized.
 
-LIB should be a string denoting a shared library without any file type
-suffix such as ".so".  The suffix is provided automatically.  It
+As for @code{dynamic-link}, @var{lib} should not contain any suffix such
+as @code{.so} (@pxref{Foreign Libraries, dynamic-link}).  It
 should also not contain any directory components.  Libraries that
 implement Guile Extensions should be put into the normal locations for
 shared libraries.  We recommend to use the naming convention
-libguile-bla-blum for a extension related to a module `(bla blum)'.
+@file{libguile-bla-blum} for a extension related to a module @code{(bla
+blum)}.
 
 The normal way for a extension to be used is to write a small Scheme
 file that defines a module, and to load the extension into this
@@ -356,10 +362,24 @@ To define C primitives within a specific module, the simplest way is:
 (load-extension "foobar-c-code" "foo_bar_init")
 @end example
 
+@cindex extensiondir
 When loaded with @code{(use-modules (foo bar))}, the
 @code{load-extension} call looks for the @file{foobar-c-code.so} (etc)
-object file in the standard system locations, such as @file{/usr/lib}
-or @file{/usr/local/lib}.
+object file in Guile's @code{extensiondir}, which is usually a
+subdirectory of the @code{libdir}. For example, if your libdir is
+@file{/usr/lib}, the @code{extensiondir} for the Guile @value{EFFECTIVE-VERSION}.@var{x}
+series will be @file{/usr/lib/guile/@value{EFFECTIVE-VERSION}/}.
+
+The extension path includes the major and minor version of Guile (the
+``effective version''), because Guile guarantees compatibility within a
+given effective version. This allows you to install different versions
+of the same extension for different versions of Guile.
+
+If the extension is not found in the @code{extensiondir}, Guile will
+also search the standard system locations, such as @file{/usr/lib} or
+@file{/usr/local/lib}. It is preferable, however, to keep your extension
+out of the system library path, to prevent unintended interference with
+other dynamically-linked C libraries.
 
 If someone installs your module to a non-standard location then the
 object file won't be found.  You can address this by inserting the
@@ -377,7 +397,7 @@ can by substituted into a source file like @file{foo.scm.in}
 
 @example
 (define-module (foo bar))
-(load-extension "XXlibdirXX/foobar-c-code" "foo_bar_init")
+(load-extension "XXextensiondirXX/foobar-c-code" "foo_bar_init")
 @end example
 
 @noindent
@@ -386,17 +406,17 @@ with the following in a @file{Makefile}, using @command{sed}
 
 @example
 foo.scm: foo.scm.in
-        sed 's|XXlibdirXX|$(libdir)|' <foo.scm.in >foo.scm
+        sed 's|XXextensiondirXX|$(libdir)/guile/@value{EFFECTIVE-VERSION}|' <foo.scm.in >foo.scm
 @end example
 
-The actual pattern @code{XXlibdirXX} is arbitrary, it's only something
+The actual pattern @code{XXextensiondirXX} is arbitrary, it's only something
 which doesn't otherwise occur.  If several modules need the value, it
 can be easier to create one @file{foo/config.scm} with a define of the
-@code{libdir} location, and use that as required.
+@code{extensiondir} location, and use that as required.
 
 @example
 (define-module (foo config))
-(define-public foo-config-libdir "XXlibdirXX"")
+(define-public foo-config-extensiondir "XXextensiondirXX"")
 @end example
 
 Such a file might have other locations too, for instance a data
@@ -404,11 +424,6 @@ directory for auxiliary files, or @code{localedir} if the module has
 its own @code{gettext} message catalogue
 (@pxref{Internationalization}).
 
-When installing multiple C code objects, it can be convenient to put
-them in a subdirectory of @code{libdir}, thus giving for example
-@code{/usr/lib/foo/some-obj.so}.  If the objects are only meant to be
-used through the module, then a subdirectory keeps them out of sight.
-
 It will be noted all of the above requires that the Scheme code to be
 found in @code{%load-path} (@pxref{Build Config}).  Presently it's
 left up to the system administrator or each user to augment that path
@@ -416,21 +431,6 @@ when installing Guile modules in non-default locations.  But having
 reached the Scheme code, that code should take care of hitting any of
 its own private files etc.
 
-Presently there's no convention for having a Guile version number in
-module C code filenames or directories.  This is primarily because
-there's no established principles for two versions of Guile to be
-installed under the same prefix (eg. two both under @file{/usr}).
-Assuming upward compatibility is maintained then this should be
-unnecessary, and if compatibility is not maintained then it's highly
-likely a package will need to be revisited anyway.
-
-The present suggestion is that modules should assume when they're
-installed under a particular @code{prefix} that there's a single
-version of Guile there, and the @code{guile-config} at build time has
-the necessary information about it.  C code or Scheme code might adapt
-itself accordingly (allowing for features not available in an older
-version for instance).
-
 
 @node Foreign Pointers
 @subsection Foreign Pointers
@@ -442,9 +442,10 @@ section takes up the problem of accessing C values from Scheme, and the
 next discusses C functions.
 
 @menu
-* Foreign Types::  foo
-* Foreign Variables::  foo
-* Foreign Pointers and Values::  foo
+* Foreign Types::                  Expressing C types in Scheme.
+* Foreign Variables::              Pointers to C symbols.
+* Void Pointers and Byte Access::  Pointers into the ether.
+* Foreign Structs::                Packing and unpacking structs.
 @end menu
 
 @node Foreign Types
@@ -454,9 +455,9 @@ The first impedance mismatch that one sees between C and Scheme is that
 in C, the storage locations (variables) are typed, but in Scheme types
 are associated with values, not variables. @xref{Values and Variables}.
 
-So when accessing a C value from Scheme, we must give the type of the
-value explicitly, as a parameter to any procedure that translates
-between Scheme and C values.
+So when describing a C function or a C structure so that it can be
+accessed from Scheme, the data types of the parameters or fields must be
+passed explicitly.
 
 These ``C type values'' may be constructed using the constants and
 procedures from the @code{(system foreign)} module, which may be loaded
@@ -469,9 +470,7 @@ like this:
 @code{(system foreign)} exports a number of values expressing the basic
 C types:
 
-@defvr {Scheme Variable} float
-@defvrx {Scheme Variable} double
-@defvrx {Scheme Variable} int8
+@defvr {Scheme Variable} int8
 @defvrx {Scheme Variable} uint8
 @defvrx {Scheme Variable} uint16
 @defvrx {Scheme Variable} int16
@@ -479,8 +478,10 @@ C types:
 @defvrx {Scheme Variable} int32
 @defvrx {Scheme Variable} uint64
 @defvrx {Scheme Variable} int64
-Values exported by the @code{(system foreign)} module, representing C
-numeric types of the specified sizes and signednesses.
+@defvrx {Scheme Variable} float
+@defvrx {Scheme Variable} double
+These values represent the C numeric types of the specified sizes and
+signednesses.
 @end defvr
 
 In addition there are some convenience bindings for indicating types of
@@ -496,22 +497,26 @@ numeric types. For example, @code{long} may be @code{equal?} to
 @code{int64} on a 64-bit platform.
 @end defvr
 
+@defvr {Scheme Variable} void
+The @code{void} type.  It can be used as the first argument to
+@code{pointer->procedure} to wrap a C function that returns nothing.
+@end defvr
+
+In addition, the symbol @code{*} is used by convention to denote pointer
+types.  Procedures detailed in the following sections, such as
+@code{pointer->procedure}, accept it as a type descriptor.
+
 @node Foreign Variables
 @subsubsection Foreign Variables
 
-Given the types defined in the previous section, foreign values may be
-looked up dynamically using @code{dynamic-pointer}.
+Pointers to variables in the current address space may be looked up
+dynamically using @code{dynamic-pointer}.
 
-@deffn {Scheme Procedure} dynamic-pointer name type dobj [len]
-@deffnx {C Function} scm_dynamic_pointer (name, type, dobj, len)
-Return a ``handle'' for the pointer @var{name} in the shared object referred to
-by @var{dobj}. The handle aliases a C value, and is declared to be of type
-@var{type}. Valid types are defined in the @code{(system foreign)} module.
-
-This facility works by asking the dynamic linker for the address of a symbol,
-then assuming that it aliases a value of a given type. Obviously, the user must
-be very careful to ensure that the value actually is of the declared type, or
-bad things will happen.
+@deffn {Scheme Procedure} dynamic-pointer name dobj
+@deffnx {C Function} scm_dynamic_pointer (name, dobj)
+Return a ``wrapped pointer'' for the symbol @var{name} in the shared
+object referred to by @var{dobj}.  The returned pointer points to a C
+object.
 
 Regardless whether your C compiler prepends an underscore @samp{_} to the global
 names in a program, you should @strong{not} include this underscore in
@@ -524,54 +529,74 @@ pointing to that foreign value, we do:
 
 @example
 (use-modules (system foreign))
-(define numptob (dynamic-pointer "scm_numptob" long (dynamic-link)))
+(define numptob (dynamic-pointer "scm_numptob" (dynamic-link)))
 numptob
-@result{} #<foreign int32 8>
+@result{} #<pointer 0x7fb35b1b4688>
 @end example
 
-@noindent
-This example shows that a @code{long} on this platform is an
-@code{int32}, and that the value pointed to by @code{numptob} is 8.
+(The next section discusses ways to dereference pointers.)
+
+A value returned by @code{dynamic-pointer} is a Scheme wrapper for a C
+pointer.
 
-@node Foreign Pointers and Values
-@subsubsection Foreign Pointers and Values
+@deffn {Scheme Procedure} pointer-address pointer
+@deffnx {C Function} scm_pointer_address pointer
+Return the numerical value of @var{pointer}.
 
-It's important at this point to conceptually separate foreign values
-from foreign pointers. @code{dynamic-pointer} gives you a foreign
-pointer. A foreign value is the semantic meaning of the bytes pointed to
-by a pointer. Only foreign pointers may be wrapped in Scheme. One may
-make a pointer to a foreign value, and wrap that as a Scheme object, but
-a bare foreign value may not be wrapped.
+@example
+(pointer-address numptob)
+@result{} 139984413364296 ; YMMV
+@end example
+@end deffn
 
-When you call @code{dynamic-pointer}, the @var{type} argument indicates
-the type to which the given symbol points, but sometimes you don't know
-that type. Sometimes you have a pointer, and you don't know what kind of
-object it references. It's simply a pointer out into the ether, into the
-@code{void}.
+@deffn {Scheme Procedure} make-pointer address [finalizer]
+Return a foreign pointer object pointing to @var{address}.  If
+@var{finalizer} is passed, it should be a pointer to a one-argument C
+function that will be called when the pointer object becomes
+unreachable.
+@end deffn
 
-Guile can wrap such a pointer, by declaring that it points to
-@code{void}.
+@deffn {Scheme Procedure} pointer? obj
+Return @code{#t} if @var{obj} is a pointer object, @code{#f} otherwise.
+@end deffn
 
-@defvr {Scheme Variable} void
-A C type, used when wrapping C pointers. @code{void} represents the type
-to which the pointer points.
+@defvr {Scheme Variable} %null-pointer
+A foreign pointer whose value is 0.
 @end defvr
 
-As an example, @code{(dynamic-pointer "foo" void bar-lib)} links in the
-@var{foo} symbol in the @var{bar-lib} library as a pointer to
-@code{void}: a @code{void*}.
+@deffn {Scheme Procedure} null-pointer? pointer
+Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
+@end deffn
 
-Void pointers may be accessed as bytevectors.
+For the purpose of passing SCM values directly to foreign functions, and
+allowing them to return SCM values, Guile also supports some unsafe
+casting operators.
 
-@deffn {Scheme Procedure} foreign->bytevector foreign [uvec_type [offset [len]]]
-@deffnx {C Function} scm_foreign_to_bytevector foreign uvec_type offset len
-Return a bytevector aliasing the memory pointed to by
-@var{foreign}.
+@deffn {Scheme Procedure} scm->pointer scm
+Return a foreign pointer object with the @code{object-address}
+of @var{scm}.
+@end deffn
+
+@deffn {Scheme Procedure} pointer->scm pointer
+Unsafely cast @var{pointer} to a Scheme object.
+Cross your fingers!
+@end deffn
+
+
+@node Void Pointers and Byte Access
+@subsubsection Void Pointers and Byte Access
 
-@var{foreign} must be a void pointer, a foreign whose type is
-@var{void}. By default, the resulting bytevector will alias
-all of the memory pointed to by @var{foreign}, from beginning
-to end, treated as a @code{vu8} array.
+Wrapped pointers are untyped, so they are essentially equivalent to C
+@code{void} pointers.  As in C, the memory region pointed to by a
+pointer can be accessed at the byte level.  This is achieved using
+@emph{bytevectors} (@pxref{Bytevectors}).  The @code{(rnrs bytevector)}
+module contains procedures that can be used to convert byte sequences to
+Scheme objects such as strings, floating point numbers, or integers.
+
+@deffn {Scheme Procedure} pointer->bytevector pointer len [offset [uvec_type]]
+@deffnx {C Function} scm_foreign_to_bytevector pointer len offset uvec_type
+Return a bytevector aliasing the @var{len} bytes pointed to by
+@var{pointer}.
 
 The user may specify an alternate default interpretation for
 the memory by passing the @var{uvec_type} argument, to indicate
@@ -580,52 +605,193 @@ that the memory is an array of elements of that type.
 @code{uniform-vector-element-type} would return, like @code{f32}
 or @code{s16}.
 
-Users may also specify that the bytevector should only alias a
-subset of the memory, by specifying @var{offset} and @var{len}
-arguments.
+When @var{offset} is passed, it specifies the offset in bytes relative
+to @var{pointer} of the memory region aliased by the returned
+bytevector.
 
 Mutating the returned bytevector mutates the memory pointed to by
-@var{foreign}, so buckle your seatbelts.
+@var{pointer}, so buckle your seatbelts.
+@end deffn
+
+@deffn {Scheme Procedure} bytevector->pointer bv [offset]
+@deffnx {C Function} scm_bytevector_to_pointer bv offset
+Return a pointer pointer aliasing the memory pointed to by @var{bv} or
+@var{offset} bytes after @var{bv} when @var{offset} is passed.
 @end deffn
 
-@deffn {Scheme Procedure} foreign-set! foreign val
-@deffnx {C Function} scm_foreign_set_x foreign val
-Set the foreign value wrapped by @var{foreign}.
+In addition to these primitives, convenience procedures are available:
 
-The value will be set according to its type.
+@deffn {Scheme Procedure} dereference-pointer pointer
+Assuming @var{pointer} points to a memory region that holds a pointer,
+return this pointer.
 @end deffn
 
-Typed pointers may be referenced using the @code{foreign-ref} and
-@code{foreign-set!} functions.
+@deffn {Scheme Procedure} string->pointer string [encoding]
+Return a foreign pointer to a nul-terminated copy of @var{string} in the
+given @var{encoding}, defaulting to the current locale encoding.  The C
+string is freed when the returned foreign pointer becomes unreachable.
 
-@deffn {Scheme Procedure} foreign-ref foreign
-@deffnx {C Function} scm_foreign_ref foreign
-Reference the foreign value wrapped by @var{foreign}.
+This is the Scheme equivalent of @code{scm_to_stringn}.
+@end deffn
 
-The value will be referenced according to its type.
+@deffn {Scheme Procedure} pointer->string pointer [length] [encoding]
+Return the string representing the C string pointed to by @var{pointer}.
+If @var{length} is omitted or @code{-1}, the string is assumed to be
+nul-terminated.  Otherwise @var{length} is the number of bytes in memory
+pointed to by @var{pointer}.  The C string is assumed to be in the given
+@var{encoding}, defaulting to the current locale encoding.
 
-@example
-(foreign-ref numptob) @result{} 8 ; YMMV
-@end example
+This is the Scheme equivalent of @code{scm_from_stringn}.
 @end deffn
 
-@deffn {Scheme Procedure} foreign-set! foreign val
-@deffnx {C Function} scm_foreign_set_x foreign val
-Set the foreign value wrapped by @var{foreign}.
+@cindex wrapped pointer types
+Most object-oriented C libraries use pointers to specific data
+structures to identify objects.  It is useful in such cases to reify the
+different pointer types as disjoint Scheme types.  The
+@code{define-wrapped-pointer-type} macro simplifies this.
+
+@deffn {Scheme Syntax} define-wrapped-pointer-type type-name pred wrap unwrap print
+Define helper procedures to wrap pointer objects into Scheme objects
+with a disjoint type.  Specifically, this macro defines:
+
+@itemize
+@item @var{pred}, a predicate for the new Scheme type;
+@item @var{wrap}, a procedure that takes a pointer object and returns an
+object that satisfies @var{pred};
+@item @var{unwrap}, which does the reverse.
+@end itemize
+
+@var{wrap} preserves pointer identity, for two pointer objects @var{p1}
+and @var{p2} that are @code{equal?}, @code{(eq? (@var{wrap} @var{p1})
+(@var{wrap} @var{p2})) @result{} #t}.
+
+Finally, @var{print} should name a user-defined procedure to print such
+objects.  The procedure is passed the wrapped object and a port to write
+to.
 
-The value will be set according to its type.
+For example, assume we are wrapping a C library that defines a type,
+@code{bottle_t}, and functions that can be passed @code{bottle_t *}
+pointers to manipulate them.  We could write:
 
 @example
-(foreign-set! numptob 120) ; Don't try this at home!
+(define-wrapped-pointer-type bottle
+  bottle?
+  wrap-bottle unwrap-bottle
+  (lambda (b p)
+    (format p "#<bottle of ~a ~x>"
+            (bottle-contents b)
+            (pointer-address (unwrap-foo b)))))
+
+(define grab-bottle
+  ;; Wrapper for `bottle_t *grab (void)'.
+  (let ((grab (pointer->procedure '*
+                                  (dynamic-func "grab_bottle" libbottle)
+                                  '())))
+    (lambda ()
+      "Return a new bottle."
+      (wrap-bottle (grab)))))
+
+(define bottle-contents
+  ;; Wrapper for `const char *bottle_contents (bottle_t *)'.
+  (let ((contents (pointer->procedure '*
+                                      (dynamic-func "bottle_contents"
+                                                     libbottle)
+                                      '(*))))
+    (lambda (b)
+      "Return the contents of B."
+      (pointer->string (contents (unwrap-bottle b))))))
+
+(write (grab-bottle))
+@result{} #<bottle of Ch@^ateau Haut-Brion 803d36>
 @end example
+
+In this example, @code{grab-bottle} is guaranteed to return a genuine
+@code{bottle} object satisfying @code{bottle?}.  Likewise,
+@code{bottle-contents} errors out when its argument is not a genuine
+@code{bottle} object.
 @end deffn
 
+Going back to the @code{scm_numptob} example above, here is how we can
+read its value as a C @code{long} integer:
+
+@example
+(use-modules (rnrs bytevectors))
+
+(bytevector-uint-ref (pointer->bytevector numptob (sizeof long))
+                     0 (native-endianness)
+                     (sizeof long))
+@result{} 8
+@end example
+
 If we wanted to corrupt Guile's internal state, we could set
 @code{scm_numptob} to another value; but we shouldn't, because that
-variable is not meant to be set. Indeed this point applies more widely:
-the C API is a dangerous place to be. Not only might setting a value
-crash your program, simply referencing a value with a wrong-sized type
-can prove equally disastrous.
+variable is not meant to be set.  Indeed this point applies more widely:
+the C API is a dangerous place to be.  Not only might setting a value
+crash your program, simply accessing the data pointed to by a dangling
+pointer or similar can prove equally disastrous.
+
+@node Foreign Structs
+@subsubsection Foreign Structs
+
+Finally, one last note on foreign values before moving on to actually
+calling foreign functions. Sometimes you need to deal with C structs,
+which requires interpreting each element of the struct according to the
+its type, offset, and alignment. Guile has some primitives to support
+this.
+
+@deffn {Scheme Procedure} sizeof type
+@deffnx {C Function} scm_sizeof type
+Return the size of @var{type}, in bytes.
+
+@var{type} should be a valid C type, like @code{int}.
+Alternately @var{type} may be the symbol @code{*}, in which
+case the size of a pointer is returned. @var{type} may
+also be a list of types, in which case the size of a
+@code{struct} with ABI-conventional packing is returned.
+@end deffn
+
+@deffn {Scheme Procedure} alignof type
+@deffnx {C Function} scm_alignof type
+Return the alignment of @var{type}, in bytes.
+
+@var{type} should be a valid C type, like @code{int}.
+Alternately @var{type} may be the symbol @code{*}, in which
+case the alignment of a pointer is returned. @var{type} may
+also be a list of types, in which case the alignment of a
+@code{struct} with ABI-conventional packing is returned.
+@end deffn
+
+Guile also provides some convenience methods to pack and unpack foreign
+pointers wrapping C structs.
+
+@deffn {Scheme Procedure} make-c-struct types vals
+Create a foreign pointer to a C struct containing @var{vals} with types
+@code{types}.
+
+@var{vals} and @code{types} should be lists of the same length.
+@end deffn
+
+@deffn {Scheme Procedure} parse-c-struct foreign types
+Parse a foreign pointer to a C struct, returning a list of values.
+
+@code{types} should be a list of C types.
+@end deffn
+
+For example, to create and parse the equivalent of a @code{struct @{
+int64_t a; uint8_t b; @}}:
+
+@example
+(parse-c-struct (make-c-struct (list int64 uint8)
+                               (list 300 43))
+                (list int64 uint8))
+@result{} (300 43)
+@end example
+
+As yet, Guile only has convenience routines to support
+conventionally-packed structs. But given the @code{bytevector->foreign}
+and @code{foreign->bytevector} routines, one can create and parse
+tightly packed structs and unions by hand. See the code for
+@code{(system foreign)} for details.
 
 
 @node Dynamic FFI
@@ -634,8 +800,8 @@ can prove equally disastrous.
 Of course, the land of C is not all nouns and no verbs: there are
 functions too, and Guile allows you to call them.
 
-@deffn {Scheme Procedure} make-foreign-function return_type func_ptr arg_types
-@deffnx {C Procedure} scm_make_foreign_function return_type func_ptr arg_types
+@deffn {Scheme Procedure} pointer->procedure return_type func_ptr arg_types
+@deffnx {C Procedure} scm_pointer_to_procedure return_type func_ptr arg_types
 Make a foreign function.
 
 Given the foreign void pointer @var{func_ptr}, its argument and
@@ -644,52 +810,162 @@ procedure that will pass arguments to the foreign function
 and return appropriate values.
 
 @var{arg_types} should be a list of foreign types.
-@code{return_type} should be a foreign type.
+@code{return_type} should be a foreign type. @xref{Foreign Types}, for
+more information on foreign types.
 @end deffn
 
-TBD
+Here is a better definition of @code{(math bessel)}:
 
-@menu
-* Foreign Structs::
-@end menu
+@example
+(define-module (math bessel)
+  #:use-module (system foreign)
+  #:export (j0))
 
+(define libm (dynamic-link "libm"))
 
-@node Foreign Structs
-@subsubsection Foreign Structs
+(define j0
+  (pointer->procedure double
+                      (dynamic-func "j0" libm)
+                      (list double)))
+@end example
+
+That's it! No C at all.
+
+Numeric arguments and return values from foreign functions are
+represented as Scheme values. For example, @code{j0} in the above
+example takes a Scheme number as its argument, and returns a Scheme
+number.
+
+Pointers may be passed to and returned from foreign functions as well.
+In that case the type of the argument or return value should be the
+symbol @code{*}, indicating a pointer. For example, the following
+code makes @code{memcpy} available to Scheme:
+
+@example
+(define memcpy
+  (let ((this (dynamic-link)))
+    (pointer->procedure '*
+                        (dynamic-func "memcpy" this)
+                        (list '* '* size_t))))
+@end example
 
-Compared to Scheme, C is a lower-level language, but it does have the
-ability to compose types into structs and unions, so Guile must support
-these as well.
+To invoke @code{memcpy}, one must pass it foreign pointers:
 
-Oftentimes one only accesses structures through pointers. In that case,
-it's easy to use void pointers and the bytevector interface to access
-structures. However C allows functions to accept and return structures
-and unions by value, on the stack, so it's necessary to be able to
-express structure and union types as Scheme values.
+@example
+(use-modules (rnrs bytevectors))
 
-Conventionally-packed st
+(define src-bits
+  (u8-list->bytevector '(0 1 2 3 4 5 6 7)))
+(define src
+  (bytevector->pointer src-bits))
+(define dest
+  (bytevector->pointer (make-bytevector 16 0)))
 
-As yet, Guile only has support for conventionally-packed structs.
-tightly-packed structs and unions will
+(memcpy dest src (bytevector-length src-bits))
+
+(bytevector->u8-list (pointer->bytevector dest 16))
+@result{} (0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0)
+@end example
 
-Note that the Scheme values for C types are just that, @emph{values},
-not names. @code{(quote int64 uint8)} won't do what you want.
+One may also pass structs as values, passing structs as foreign
+pointers. @xref{Foreign Structs}, for more information on how to express
+struct types and struct values.
 
-C does not only have numeric types; one other type that it has is the
-@dfn{struct}, which in Guile is represented as a list of C types, so
-that the following two type declarations are equivalent:
+``Out'' arguments are passed as foreign pointers. The memory pointed to
+by the foreign pointer is mutated in place.
 
 @example
-struct @{ int64_t foo; uint8_t bar; @}
-(list int64 uint8)
+;; struct timeval @{
+;;      time_t      tv_sec;     /* seconds */
+;;      suseconds_t tv_usec;    /* microseconds */
+;; @};
+;; assuming fields are of type "long"
+
+(define gettimeofday
+  (let ((f (pointer->procedure
+            int
+            (dynamic-func "gettimeofday" (dynamic-link))
+            (list '* '*)))
+        (tv-type (list long long)))
+    (lambda ()
+      (let* ((timeval (make-c-struct tv-type (list 0 0)))
+             (ret (f timeval %null-pointer)))
+        (if (zero? ret)
+            (apply values (parse-c-struct timeval tv-type))
+            (error "gettimeofday returned an error" ret))))))
+
+(gettimeofday)    
+@result{} 1270587589
+@result{} 499553
 @end example
 
-Putting Scheme types in a list is the same as declaring a struct type
-with the default packing. Guile does not currently support
-tightly-packed structs; in that case you should declare the value as
-being a void pointer, and access the bytes as a bytevector.
+As you can see, this interface to foreign functions is at a very low,
+somewhat dangerous level@footnote{A contribution to Guile in the form of
+a high-level FFI would be most welcome.}.
+
+@cindex callbacks
+The FFI can also work in the opposite direction: making Scheme
+procedures callable from C.  This makes it possible to use Scheme
+procedures as ``callbacks'' expected by C function.
+
+@deffn {Scheme Procedure} procedure->pointer return-type proc arg-types
+@deffnx {C Function} scm_procedure_to_pointer (return_type, proc, arg_types)
+Return a pointer to a C function of type @var{return-type}
+taking arguments of types @var{arg-types} (a list) and
+behaving as a proxy to procedure @var{proc}.  Thus
+@var{proc}'s arity, supported argument types, and return
+type should match @var{return-type} and @var{arg-types}.
+@end deffn
+
+As an example, here's how the C library's @code{qsort} array sorting
+function can be made accessible to Scheme (@pxref{Array Sort Function,
+@code{qsort},, libc, The GNU C Library Reference Manual}):
+
+@example
+(define qsort!
+  (let ((qsort (pointer->procedure void
+                                   (dynamic-func "qsort"
+                                                 (dynamic-link))
+                                   (list '* size_t size_t '*))))
+    (lambda (bv compare)
+      ;; Sort bytevector BV in-place according to comparison
+      ;; procedure COMPARE.
+      (let ((ptr (procedure->pointer int
+                                     (lambda (x y)
+                                       ;; X and Y are pointers so,
+                                       ;; for convenience, dereference
+                                       ;; them before calling COMPARE.
+                                       (compare (dereference-uint8* x)
+                                                (dereference-uint8* y)))
+                                     (list '* '*))))
+        (qsort (bytevector->pointer bv)
+               (bytevector-length bv) 1 ;; we're sorting bytes
+               ptr)))))
+
+(define (dereference-uint8* ptr)
+  ;; Helper function: dereference the byte pointed to by PTR.
+  (let ((b (pointer->bytevector ptr 1)))
+    (bytevector-u8-ref b 0)))
+
+(define bv
+  ;; An unsorted array of bytes.
+  (u8-list->bytevector '(7 1 127 3 5 4 77 2 9 0)))
+
+;; Sort BV.
+(qsort! bv (lambda (x y) (- x y)))
+
+;; Let's see what the sorted array looks like:
+(bytevector->u8-list bv)
+@result{} (0 1 2 3 4 5 7 9 77 127)
+@end example
 
+And voil@`a!
 
+Note that @code{procedure->pointer} is not supported (and not defined)
+on a few exotic architectures.  Thus, user code may need to check
+@code{(defined? 'procedure->pointer)}.  Nevertheless, it is available on
+many architectures, including (as of libffi 3.0.9) x86, ia64, SPARC,
+PowerPC, ARM, and MIPS, to name a few.
 
 @c Local Variables:
 @c TeX-master: "guile.texi"