code:
@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 See the file guile.texi for copying conditions.

@page
@node Foreign Function Interface
@section Foreign Function Interface
@cindex foreign function interface
@cindex ffi

The more one hacks in Scheme, the more one realizes that there are
actually two computational worlds: one which is warm and alive, that
land of parentheses, and one cold and dead, the land of C and its ilk.

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.

@menu
* Foreign Libraries::           Dynamically linking to libraries.
* Foreign Functions::           Simple calls to C procedures.
* C Extensions::                Extending Guile in C with loadable modules.
* Modules and Extensions::      Loading C extensions into modules.
* Foreign Pointers::            Accessing global variables.
* Dynamic FFI::                 Calling arbitrary C functions.
@end menu

@node Foreign Libraries
@subsection Foreign Libraries

Most modern Unices have something called @dfn{shared libraries}.  This
ordinarily means that they have the capability to share the executable
image of a library between several running programs to save memory and
disk space.  But generally, shared libraries give a lot of additional
flexibility compared to the traditional static libraries.  In fact,
calling them `dynamic' libraries is as correct as calling them `shared'.

Shared libraries really give you a lot of flexibility in addition to the
memory and disk space savings.  When you link a program against a shared
library, that library is not closely incorporated into the final
executable.  Instead, the executable of your program only contains
enough information to find the needed shared libraries when the program
is actually run.  Only then, when the program is starting, is the final
step of the linking process performed.  This means that you need not
recompile all programs when you install a new, only slightly modified
version of a shared library.  The programs will pick up the changes
automatically the next time they are run.

Now, when all the necessary machinery is there to perform part of the
linking at run-time, why not take the next step and allow the programmer
to explicitly take advantage of it from within his program?  Of course,
many operating systems that support shared libraries do just that, and
chances are that Guile will allow you to access this feature from within
your Scheme programs.  As you might have guessed already, this feature
is called @dfn{dynamic linking}.@footnote{Some people also refer to the
final linking stage at program startup as `dynamic linking', so if you
want to make yourself perfectly clear, it is probably best to use the
more technical term @dfn{dlopening}, as suggested by Gordon Matzigkeit
in his libtool documentation.}

We titled this section ``foreign libraries'' because although the name
``foreign'' doesn't leak into the API, the world of C really is foreign
to Scheme -- and that estrangement extends to components of foreign
libraries as well, as we see in future sections.

@deffn {Scheme Procedure} dynamic-link [library]
@deffnx {C Function} scm_dynamic_link (library)
Find the shared library denoted by @var{library} (a string) and link it
into the running Guile application.  When everything works out, return a
Scheme object suitable for representing the linked object file.
Otherwise an error is thrown.  How object files are searched is system
dependent.

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

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
loaded.
@end deffn

@deffn {Scheme Procedure} dynamic-object? obj
@deffnx {C Function} scm_dynamic_object_p (obj)
Return @code{#t} if @var{obj} is a dynamic library handle, or @code{#f}
otherwise.
@end deffn

@deffn {Scheme Procedure} dynamic-unlink dobj
@deffnx {C Function} scm_dynamic_unlink (dobj)
Unlink the indicated object file from the application.  The
argument @var{dobj} must have been obtained by a call to
@code{dynamic-link}.  After @code{dynamic-unlink} has been
called on @var{dobj}, its content is no longer accessible.
@end deffn

@smallexample
(define libgl-obj (dynamic-link "libGL"))
libgl-obj
@result{} #<dynamic-object "libGL">
(dynamic-unlink libGL-obj)
libGL-obj
@result{} #<dynamic-object "libGL" (unlinked)>
@end smallexample

As you can see, after calling @code{dynamic-unlink} on a dynamically
linked library, it is marked as @samp{(unlinked)} and you are no longer
able to use it with @code{dynamic-call}, etc.  Whether the library is
really removed from you program is system-dependent and will generally
not happen when some other parts of your program still use it.

When dynamic linking is disabled or not supported on your system,
the above functions throw errors, but they are still available.

@node Foreign Functions
@subsection Foreign Functions

The most natural thing to do with a dynamic library is to grovel around
in it for a function pointer: a @dfn{foreign function}.
@code{dynamic-func} exists for that purpose.

@deffn {Scheme Procedure} dynamic-func name dobj
@deffnx {C Function} scm_dynamic_func (name, dobj)
Return a ``handle'' for the func @var{name} in the shared object referred to
by @var{dobj}. The handle can be passed to @code{dynamic-call} to
actually call the function.

Regardless whether your C compiler prepends an underscore @samp{_} to the global
names in a program, you should @strong{not} include this underscore in
@var{name} since it will be added automatically when necessary.
@end deffn

Guile has static support for calling functions with no arguments,
@code{dynamic-call}.

@deffn {Scheme Procedure} dynamic-call func dobj
@deffnx {C Function} scm_dynamic_call (func, dobj)
Call the C function indicated by @var{func} and @var{dobj}.
The function is passed no arguments and its return value is
ignored.  When @var{function} is something returned by
@code{dynamic-func}, call that function and ignore @var{dobj}.
When @var{func} is a string , look it up in @var{dynobj}; this
is equivalent to
@smallexample
(dynamic-call (dynamic-func @var{func} @var{dobj}) #f)
@end smallexample

Interrupts are deferred while the C function is executing (with
@code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}).
@end deffn

@code{dynamic-call} is not very powerful. It is mostly intended to be
used for calling specially written initialization functions that will
then add new primitives to Guile. For example, we do not expect that you
will dynamically link @file{libX11} with @code{dynamic-link} and then
construct a beautiful graphical user interface just by using
@code{dynamic-call}. Instead, the usual way would be to write a special
Guile-to-X11 glue library that has intimate knowledge about both Guile
and X11 and does whatever is necessary to make them inter-operate
smoothly. This glue library could then be dynamically linked into a
vanilla Guile interpreter and activated by calling its initialization
function. That function would add all the new types and primitives to
the Guile interpreter that it has to offer.

(There is actually another, better option: simply to create a
@file{libX11} wrapper in Scheme via the dynamic FFI. @xref{Dynamic FFI},
for more information.)

Given some set of C extensions to Guile, the next logical step is to
integrate these glue libraries into the module system of Guile so that
you can load new primitives into a running system just as you can load
new Scheme code.

@deffn {Scheme Procedure} load-extension lib init
@deffnx {C Function} scm_load_extension (lib, init)
Load and initialize the extension designated by LIB and INIT.
When there is no pre-registered function for LIB/INIT, this is
equivalent to

@lisp
(dynamic-call INIT (dynamic-link LIB))
@end lisp

When there is a pre-registered function, that function is called
instead.

Normally, there is no pre-registered function.  This option exists
only for situations where dynamic linking is unavailable or unwanted.
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
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)'.

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
module.  When the module is auto-loaded, the extension is loaded as
well.  For example,

@lisp
(define-module (bla blum))

(load-extension "libguile-bla-blum" "bla_init_blum")
@end lisp
@end deffn

@node C Extensions
@subsection C Extensions

The most interesting application of dynamically linked libraries is
probably to use them for providing @emph{compiled code modules} to
Scheme programs.  As much fun as programming in Scheme is, every now and
then comes the need to write some low-level C stuff to make Scheme even
more fun.

Not only can you put these new primitives into their own module (see the
previous section), you can even put them into a shared library that is
only then linked to your running Guile image when it is actually
needed.

An example will hopefully make everything clear.  Suppose we want to
make the Bessel functions of the C library available to Scheme in the
module @samp{(math bessel)}.  First we need to write the appropriate
glue code to convert the arguments and return values of the functions
from Scheme to C and back.  Additionally, we need a function that will
add them to the set of Guile primitives.  Because this is just an
example, we will only implement this for the @code{j0} function.

@smallexample
#include <math.h>
#include <libguile.h>

SCM
j0_wrapper (SCM x)
@{
  return scm_from_double (j0 (scm_to_double (x, "j0")));
@}

void
init_math_bessel ()
@{
  scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
@}
@end smallexample

We can already try to bring this into action by manually calling the low
level functions for performing dynamic linking.  The C source file needs
to be compiled into a shared library.  Here is how to do it on
GNU/Linux, please refer to the @code{libtool} documentation for how to
create dynamically linkable libraries portably.

@smallexample
gcc -shared -o libbessel.so -fPIC bessel.c
@end smallexample

Now fire up Guile:

@lisp
(define bessel-lib (dynamic-link "./libbessel.so"))
(dynamic-call "init_math_bessel" bessel-lib)
(j0 2)
@result{} 0.223890779141236
@end lisp

The filename @file{./libbessel.so} should be pointing to the shared
library produced with the @code{gcc} command above, of course.  The
second line of the Guile interaction will call the
@code{init_math_bessel} function which in turn will register the C
function @code{j0_wrapper} with the Guile interpreter under the name
@code{j0}.  This function becomes immediately available and we can call
it from Scheme.

Fun, isn't it?  But we are only half way there.  This is what
@code{apropos} has to say about @code{j0}:

@smallexample
(apropos "j0")
@print{} (guile-user): j0     #<primitive-procedure j0>
@end smallexample

As you can see, @code{j0} is contained in the root module, where all
the other Guile primitives like @code{display}, etc live.  In general,
a primitive is put into whatever module is the @dfn{current module} at
the time @code{scm_c_define_gsubr} is called.

A compiled module should have a specially named @dfn{module init
function}.  Guile knows about this special name and will call that
function automatically after having linked in the shared library.  For
our example, we replace @code{init_math_bessel} with the following code in
@file{bessel.c}:

@smallexample
void
init_math_bessel (void *unused)
@{
  scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
  scm_c_export ("j0", NULL);
@}

void
scm_init_math_bessel_module ()
@{
  scm_c_define_module ("math bessel", init_math_bessel, NULL);
@}
@end smallexample

The general pattern for the name of a module init function is:
@samp{scm_init_}, followed by the name of the module where the
individual hierarchical components are concatenated with underscores,
followed by @samp{_module}.

After @file{libbessel.so} has been rebuilt, we need to place the shared
library into the right place.

Once the module has been correctly installed, it should be possible to
use it like this:

@smallexample
guile> (load-extension "./libbessel.so" "scm_init_math_bessel_module")
guile> (use-modules (math bessel))
guile> (j0 2)
0.223890779141236
guile> (apropos "j0")
@print{} (math bessel): j0      #<primitive-procedure j0>
@end smallexample

That's it!

@node Modules and Extensions
@subsection Modules and Extensions

The new primitives that you add to Guile with @code{scm_c_define_gsubr}
(@pxref{Primitive Procedures}) or with any of the other mechanisms are
placed into the module that is current when the
@code{scm_c_define_gsubr} is executed. Extensions loaded from the REPL,
for example, will be placed into the @code{(guile-user)} module, if the
REPL module was not changed.

To define C primitives within a specific module, the simplest way is:

@example
(define-module (foo bar))
(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 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 2.0.@var{x}
series will be @file{/usr/lib/guile/2.0/}.

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
install location in the @file{foo/bar.scm} file.  This is convenient
for the user and also guarantees the intended object is read, even if
stray older or newer versions are in the loader's path.

The usual way to specify an install location is with a @code{prefix}
at the configure stage, for instance @samp{./configure prefix=/opt}
results in library files as say @file{/opt/lib/foobar-c-code.so}.
When using Autoconf (@pxref{Top, , Introduction, autoconf, The GNU
Autoconf Manual}), the library location is in a @code{libdir}
variable.  Its value is intended to be expanded by @command{make}, and
can by substituted into a source file like @file{foo.scm.in}

@example
(define-module (foo bar))
(load-extension "XXextensiondirXX/foobar-c-code" "foo_bar_init")
@end example

@noindent
with the following in a @file{Makefile}, using @command{sed}
(@pxref{Top, , Introduction, sed, SED, A Stream Editor}),

@example
foo.scm: foo.scm.in
        sed 's|XXextensiondirXX|$(libdir)/guile/2.0|' <foo.scm.in >foo.scm
@end example

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{extensiondir} location, and use that as required.

@example
(define-module (foo config))
(define-public foo-config-extensiondir "XXextensiondirXX"")
@end example

Such a file might have other locations too, for instance a data
directory for auxiliary files, or @code{localedir} if the module has
its own @code{gettext} message catalogue
(@pxref{Internationalization}).

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

@node Foreign Pointers
@subsection Foreign Pointers

The previous sections have shown how Guile can be extended at runtime by
loading compiled C extensions. This approach is all well and good, but
wouldn't it be nice if we didn't have to write any C at all? This
section takes up the problem of accessing C values from Scheme, and the
next discusses C functions.

@menu
* 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
@subsubsection Foreign Types

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 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
like this:

@example
(use-modules (system foreign))
@end example

@code{(system foreign)} exports a number of values expressing the basic
C types:

@defvr {Scheme Variable} int8
@defvrx {Scheme Variable} uint8
@defvrx {Scheme Variable} uint16
@defvrx {Scheme Variable} int16
@defvrx {Scheme Variable} uint32
@defvrx {Scheme Variable} int32
@defvrx {Scheme Variable} uint64
@defvrx {Scheme Variable} int64
@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
platform-dependent size:

@defvr {Scheme Variable} int
@defvrx {Scheme Variable} unsigned-int
@defvrx {Scheme Variable} long
@defvrx {Scheme Variable} unsigned-long
@defvrx {Scheme Variable} size_t
Values exported by the @code{(system foreign)} module, representing C
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{make-foreign-function} to wrap a C function that returns nothing.
@end defvr

@node Foreign Variables
@subsubsection Foreign Variables

Pointers to variables in the current address space may be looked up
dynamically using @code{dynamic-pointer}.

@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
@var{name} since it will be added automatically when necessary.
@end deffn

For example, currently Guile has a variable, @code{scm_numptob}, as part
of its API. It is declared as a C @code{long}. So, to create a handle
pointing to that foreign value, we do:

@example
(use-modules (system foreign))
(define numptob (dynamic-pointer "scm_numptob" (dynamic-link)))
numptob
@result{} #<pointer 0x7fb35b1b4688>
@end example

(The next section discusses ways to dereference pointers.)

A value returned by @code{dynamic-pointer} is a Scheme wrapper for a C
pointer.

@deffn {Scheme Procedure} pointer-address pointer
@deffnx {C Function} scm_pointer_address pointer
Return the numerical value of @var{pointer}.

@example
(pointer-address numptob)
@result{} 139984413364296 ; YMMV
@end example
@end deffn

@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

@defvr {Scheme Variable} %null-pointer
A foreign pointer whose value is 0.
@end defvr

@deffn {Scheme Procedure} null-pointer? pointer
Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
@end deffn

@node Void Pointers and Byte Access
@subsubsection Void Pointers and Byte Access

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
that the memory is an array of elements of that type.
@var{uvec_type} should be something that
@code{uniform-vector-element-type} would return, like @code{f32}
or @code{s16}.

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{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

In addition to these primitives, convenience procedures are available:

@deffn {Scheme Procedure} dereference-pointer pointer
Assuming @var{pointer} points to a memory region that holds a pointer,
return this pointer.
@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 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
@subsection Dynamic FFI

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
Make a foreign function.

Given the foreign void pointer @var{func_ptr}, its argument and
return types @var{arg_types} and @var{return_type}, return a
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. @xref{Foreign Types}, for
more information on foreign types.
@end deffn

Here is a better definition of @code{(math bessel)}:

@example
(define-module (math bessel)
  #:use-module (system foreign)
  #:export (j0))

(define libm (dynamic-link "libm"))

(define j0
  (make-foreign-function 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)))
    (make-foreign-function '*
                           (dynamic-func "memcpy" this)
                           (list '* '* size_t))))
@end example

To invoke @code{memcpy}, one must pass it foreign pointers:

@example
(use-modules (rnrs bytevectors))

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

(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

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.

``Out'' arguments are passed as foreign pointers. The memory pointed to
by the foreign pointer is mutated in place.

@example
;; struct timeval @{
;;      time_t      tv_sec;     /* seconds */
;;      suseconds_t tv_usec;    /* microseconds */
;; @};
;; assuming fields are of type "long"

(define gettimeofday
  (let ((f (make-foreign-function
            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

As you can see, this interface to foreign functions is at a very low,
somewhat dangerous level. A contribution to Guile in the form of a
high-level FFI would be most welcome.

@c Local Variables:
@c TeX-master: "guile.texi"
@c End:


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2009, 2010
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Internationalization
@section Support for Internationalization

@cindex internationalization
@cindex i18n

Guile provides internationalization@footnote{For concision and style,
programmers often like to refer to internationalization as ``i18n''.}
support for Scheme programs in two ways.  First, procedures to
manipulate text and data in a way that conforms to particular cultural
conventions (i.e., in a ``locale-dependent'' way) are provided in the
@code{(ice-9 i18n)}.  Second, Guile allows the use of GNU
@code{gettext} to translate program message strings.

@menu
* i18n Introduction::             Introduction to Guile's i18n support.
* Text Collation::                Sorting strings and characters.
* Character Case Mapping::        Case mapping.
* Number Input and Output::       Parsing and printing numbers.
* Accessing Locale Information::  Detailed locale information.
* Gettext Support::               Translating message strings.
@end menu

@node i18n Introduction, Text Collation, Internationalization, Internationalization
@subsection Internationalization with Guile

In order to make use of the functions described thereafter, the
@code{(ice-9 i18n)} module must be imported in the usual way:

@example
(use-modules (ice-9 i18n))
@end example

@cindex cultural conventions

The @code{(ice-9 i18n)} module provides procedures to manipulate text
and other data in a way that conforms to the cultural conventions
chosen by the user.  Each region of the world or language has its own
customs to, for instance, represent real numbers, classify characters,
collate text, etc.  All these aspects comprise the so-called
``cultural conventions'' of that region or language.

@cindex locale
@cindex locale category

Computer systems typically refer to a set of cultural conventions as a
@dfn{locale}.  For each particular aspect that comprise those cultural
conventions, a @dfn{locale category} is defined.  For instance, the
way characters are classified is defined by the @code{LC_CTYPE}
category, while the language in which program messages are issued to
the user is defined by the @code{LC_MESSAGES} category
(@pxref{Locales, General Locale Information} for details).

@cindex locale object

The procedures provided by this module allow the development of
programs that adapt automatically to any locale setting.  As we will
see later, many of these procedures can optionally take a @dfn{locale
object} argument.  This additional argument defines the locale
settings that must be followed by the invoked procedure.  When it is
omitted, then the current locale settings of the process are followed
(@pxref{Locales, @code{setlocale}}).

The following procedures allow the manipulation of such locale
objects.

@deffn {Scheme Procedure} make-locale category-list locale-name [base-locale]
@deffnx {C Function} scm_make_locale (category_list, locale_name, base_locale)
Return a reference to a data structure representing a set of locale
datasets.  @var{locale-name} should be a string denoting a particular
locale (e.g., @code{"aa_DJ"}) and @var{category-list} should be either
a list of locale categories or a single category as used with
@code{setlocale} (@pxref{Locales, @code{setlocale}}).  Optionally, if
@code{base-locale} is passed, it should be a locale object denoting
settings for categories not listed in @var{category-list}.

The following invocation creates a locale object that combines the use
of Swedish for messages and character classification with the
default settings for the other categories (i.e., the settings of the
default @code{C} locale which usually represents conventions in use in
the USA):

@example
(make-locale (list LC_MESSAGE LC_CTYPE) "sv_SE")
@end example

The following example combines the use of Esperanto messages and
conventions with monetary conventions from Croatia:

@example
(make-locale LC_MONETARY "hr_HR"
             (make-locale LC_ALL "eo_EO"))
@end example

A @code{system-error} exception (@pxref{Handling Errors}) is raised by
@code{make-locale} when @var{locale-name} does not match any of the
locales compiled on the system.  Note that on non-GNU systems, this
error may be raised later, when the locale object is actually used.

@end deffn

@deffn {Scheme Procedure} locale? obj
@deffnx {C Function} scm_locale_p (obj)
Return true if @var{obj} is a locale object.
@end deffn

@defvr {Scheme Variable} %global-locale
@defvrx {C Variable} scm_global_locale
This variable is bound to a locale object denoting the current process
locale as installed using @code{setlocale ()} (@pxref{Locales}).  It
may be used like any other locale object, including as a third
argument to @code{make-locale}, for instance.
@end defvr

@node Text Collation, Character Case Mapping, i18n Introduction, Internationalization
@subsection Text Collation

The following procedures provide support for text collation, i.e.,
locale-dependent string and character sorting.

@deffn {Scheme Procedure} string-locale<? s1 s2 [locale]
@deffnx {C Function} scm_string_locale_lt (s1, s2, locale)
@deffnx {Scheme Procedure} string-locale>? s1 s2 [locale]
@deffnx {C Function} scm_string_locale_gt (s1, s2, locale)
@deffnx {Scheme Procedure} string-locale-ci<? s1 s2 [locale]
@deffnx {C Function} scm_string_locale_ci_lt (s1, s2, locale)
@deffnx {Scheme Procedure} string-locale-ci>? s1 s2 [locale]
@deffnx {C Function} scm_string_locale_ci_gt (s1, s2, locale)
Compare strings @var{s1} and @var{s2} in a locale-dependent way.  If
@var{locale} is provided, it should be locale object (as returned by
@code{make-locale}) and will be used to perform the comparison;
otherwise, the current system locale is used.  For the @code{-ci}
variants, the comparison is made in a case-insensitive way.
@end deffn

@deffn {Scheme Procedure} string-locale-ci=? s1 s2 [locale]
@deffnx {C Function} scm_string_locale_ci_eq (s1, s2, locale)
Compare strings @var{s1} and @var{s2} in a case-insensitive, and
locale-dependent way.  If @var{locale} is provided, it should be
a locale object (as returned by @code{make-locale}) and will be used to
perform the comparison; otherwise, the current system locale is used.
@end deffn

@deffn {Scheme Procedure} char-locale<? c1 c2 [locale]
@deffnx {C Function} scm_char_locale_lt (c1, c2, locale)
@deffnx {Scheme Procedure} char-locale>? c1 c2 [locale]
@deffnx {C Function} scm_char_locale_gt (c1, c2, locale)
@deffnx {Scheme Procedure} char-locale-ci<? c1 c2 [locale]
@deffnx {C Function} scm_char_locale_ci_lt (c1, c2, locale)
@deffnx {Scheme Procedure} char-locale-ci>? c1 c2 [locale]
@deffnx {C Function} scm_char_locale_ci_gt (c1, c2, locale)
Compare characters @var{c1} and @var{c2} according to either
@var{locale} (a locale object as returned by @code{make-locale}) or
the current locale.  For the @code{-ci} variants, the comparison is
made in a case-insensitive way.
@end deffn

@deffn {Scheme Procedure} char-locale-ci=? c1 c2 [locale]
@deffnx {C Function} scm_char_locale_ci_eq (c1, c2, locale)
Return true if character @var{c1} is equal to @var{c2}, in a case
insensitive way according to @var{locale} or to the current locale.
@end deffn

@node Character Case Mapping, Number Input and Output, Text Collation, Internationalization
@subsection Character Case Mapping

The procedures below provide support for ``character case mapping'',
i.e., to convert characters or strings to their upper-case or
lower-case equivalent.  Note that SRFI-13 provides procedures that
look similar (@pxref{Alphabetic Case Mapping}).  However, the SRFI-13
procedures are locale-independent.  Therefore, they do not take into
account specificities of the customs in use in a particular language
or region of the world.  For instance, while most languages using the
Latin alphabet map lower-case letter ``i'' to upper-case letter ``I'',
Turkish maps lower-case ``i'' to ``Latin capital letter I with dot
above''.  The following procedures allow programmers to provide
idiomatic character mapping.

@deffn {Scheme Procedure} char-locale-downcase chr [locale]
@deffnx {C Function} scm_char_locale_upcase (chr, locale)
Return the lowercase character that corresponds to @var{chr} according
to either @var{locale} or the current locale.
@end deffn

@deffn {Scheme Procedure} char-locale-upcase chr [locale]
@deffnx {C Function} scm_char_locale_downcase (chr, locale)
Return the uppercase character that corresponds to @var{chr} according
to either @var{locale} or the current locale.
@end deffn

@deffn {Scheme Procedure} char-locale-titlecase chr [locale]
@deffnx {C Function} scm_char_locale_titlecase (chr, locale)
Return the titlecase character that corresponds to @var{chr} according
to either @var{locale} or the current locale.
@end deffn

@deffn {Scheme Procedure} string-locale-upcase str [locale]
@deffnx {C Function} scm_string_locale_upcase (str, locale)
Return a new string that is the uppercase version of @var{str}
according to either @var{locale} or the current locale.
@end deffn

@deffn {Scheme Procedure} string-locale-downcase str [locale]
@deffnx {C Function} scm_string_locale_downcase (str, locale)
Return a new string that is the down-case version of @var{str}
according to either @var{locale} or the current locale.
@end deffn

@deffn {Scheme Procedure} string-locale-titlecase str [locale]
@deffnx {C Function} scm_string_locale_titlecase (str, locale)
Return a new string that is the titlecase version of @var{str}
according to either @var{locale} or the current locale.
@end deffn

@node Number Input and Output, Accessing Locale Information, Character Case Mapping, Internationalization
@subsection Number Input and Output

The following procedures allow programs to read and write numbers
written according to a particular locale.  As an example, in English,
``ten thousand and a half'' is usually written @code{10,000.5} while
in French it is written @code{10 000,5}.  These procedures allow such
differences to be taken into account.

@findex strtod
@deffn {Scheme Procedure} locale-string->integer str [base [locale]]
@deffnx {C Function} scm_locale_string_to_integer (str, base, locale)
Convert string @var{str} into an integer according to either
@var{locale} (a locale object as returned by @code{make-locale}) or
the current process locale.  If @var{base} is specified, then it
determines the base of the integer being read (e.g., @code{16} for an
hexadecimal number, @code{10} for a decimal number); by default,
decimal numbers are read.  Return two values (@pxref{Multiple
Values}): an integer (on success) or @code{#f}, and the number of
characters read from @var{str} (@code{0} on failure).

This function is based on the C library's @code{strtol} function
(@pxref{Parsing of Integers, @code{strtol},, libc, The GNU C Library
Reference Manual}).
@end deffn

@findex strtod
@deffn {Scheme Procedure} locale-string->inexact str [locale]
@deffnx {C Function} scm_locale_string_to_inexact (str, locale)
Convert string @var{str} into an inexact number according to either
@var{locale} (a locale object as returned by @code{make-locale}) or
the current process locale.  Return two values (@pxref{Multiple
Values}): an inexact number (on success) or @code{#f}, and the number
of characters read from @var{str} (@code{0} on failure).

This function is based on the C library's @code{strtod} function
(@pxref{Parsing of Floats, @code{strtod},, libc, The GNU C Library
Reference Manual}).
@end deffn

@deffn {Scheme Procedure} number->locale-string number [fraction-digits [locale]]
Convert @var{number} (an inexact) into a string according to the
cultural conventions of either @var{locale} (a locale object) or the
current locale.  Optionally, @var{fraction-digits} may be bound to an
integer specifying the number of fractional digits to be displayed.
@end deffn

@deffn {Scheme Procedure} monetary-amount->locale-string amount intl? [locale]
Convert @var{amount} (an inexact denoting a monetary amount) into a
string according to the cultural conventions of either @var{locale} (a
locale object) or the current locale.  If @var{intl?} is true, then
the international monetary format for the given locale is used
(@pxref{Currency Symbol, international and locale monetary formats,,
libc, The GNU C Library Reference Manual}).
@end deffn

@node Accessing Locale Information, Gettext Support, Number Input and Output, Internationalization
@subsection Accessing Locale Information

@findex nl_langinfo
@cindex low-level locale information
It is sometimes useful to obtain very specific information about a
locale such as the word it uses for days or months, its format for
representing floating-point figures, etc.  The @code{(ice-9 i18n)}
module provides support for this in a way that is similar to the libc
functions @code{nl_langinfo ()} and @code{localeconv ()}
(@pxref{Locale Information, accessing locale information from C,,
libc, The GNU C Library Reference Manual}).  The available functions
are listed below.

@deffn {Scheme Procedure} locale-encoding [locale]
Return the name of the encoding (a string whose interpretation is
system-dependent) of either @var{locale} or the current locale.
@end deffn

The following functions deal with dates and times.

@deffn {Scheme Procedure} locale-day day [locale]
@deffnx {Scheme Procedure} locale-day-short day [locale]
@deffnx {Scheme Procedure} locale-month month [locale]
@deffnx {Scheme Procedure} locale-month-short month [locale]
Return the word (a string) used in either @var{locale} or the current
locale to name the day (or month) denoted by @var{day} (or
@var{month}), an integer between 1 and 7 (or 1 and 12).  The
@code{-short} variants provide an abbreviation instead of a full name.
@end deffn

@deffn {Scheme Procedure} locale-am-string [locale]
@deffnx {Scheme Procedure} locale-pm-string [locale]
Return a (potentially empty) string that is used to denote @i{ante
meridiem} (or @i{post meridiem}) hours in 12-hour format.
@end deffn

@deffn {Scheme Procedure} locale-date+time-format [locale]
@deffnx {Scheme Procedure} locale-date-format [locale]
@deffnx {Scheme Procedure} locale-time-format [locale]
@deffnx {Scheme Procedure} locale-time+am/pm-format [locale]
@deffnx {Scheme Procedure} locale-era-date-format [locale]
@deffnx {Scheme Procedure} locale-era-date+time-format [locale]
@deffnx {Scheme Procedure} locale-era-time-format [locale]
These procedures return format strings suitable to @code{strftime}
(@pxref{Time}) that may be used to display (part of) a date/time
according to certain constraints and to the conventions of either
@var{locale} or the current locale (@pxref{The Elegant and Fast Way,
the @code{nl_langinfo ()} items,, libc, The GNU C Library Reference
Manual}).
@end deffn

@deffn {Scheme Procedure} locale-era [locale]
@deffnx {Scheme Procedure} locale-era-year [locale]
These functions return, respectively, the era and the year of the
relevant era used in @var{locale} or the current locale.  Most locales
do not define this value.  In this case, the empty string is returned.
An example of a locale that does define this value is the Japanese
one.
@end deffn

The following procedures give information about number representation.

@deffn {Scheme Procedure} locale-decimal-point [locale]
@deffnx {Scheme Procedure} locale-thousands-separator [locale]
These functions return a string denoting the representation of the
decimal point or that of the thousand separator (respectively) for
either @var{locale} or the current locale.
@end deffn

@deffn {Scheme Procedure} locale-digit-grouping [locale]
Return a (potentially circular) list of integers denoting how digits
of the integer part of a number are to be grouped, starting at the
decimal point and going to the left.  The list contains integers
indicating the size of the successive groups, from right to left.  If
the list is non-circular, then no grouping occurs for digits beyond
the last group.

For instance, if the returned list is a circular list that contains
only @code{3} and the thousand separator is @code{","} (as is the case
with English locales), then the number @code{12345678} should be
printed @code{12,345,678}.
@end deffn

The following procedures deal with the representation of monetary
amounts.  Some of them take an additional @var{intl?} argument (a
boolean) that tells whether the international or local monetary
conventions for the given locale are to be used.

@deffn {Scheme Procedure} locale-monetary-decimal-point [locale]
@deffnx {Scheme Procedure} locale-monetary-thousands-separator [locale]
@deffnx {Scheme Procedure} locale-monetary-grouping [locale]
These are the monetary counterparts of the above procedures.  These
procedures apply to monetary amounts.
@end deffn

@deffn {Scheme Procedure} locale-currency-symbol intl? [locale]
Return the currency symbol (a string) of either @var{locale} or the
current locale.

The following example illustrates the difference between the local and
international monetary formats:

@example
(define us (make-locale LC_MONETARY "en_US"))
(locale-currency-symbol #f us)
@result{} "-$"
(locale-currency-symbol #t us)
@result{} "USD "
@end example
@end deffn

@deffn {Scheme Procedure} locale-monetary-fractional-digits intl? [locale]
Return the number of fractional digits to be used when printing
monetary amounts according to either @var{locale} or the current
locale.  If the locale does not specify it, then @code{#f} is
returned.
@end deffn

@deffn {Scheme Procedure} locale-currency-symbol-precedes-positive? intl? [locale]
@deffnx {Scheme Procedure} locale-currency-symbol-precedes-negative? intl? [locale]
@deffnx {Scheme Procedure} locale-positive-separated-by-space? intl? [locale]
@deffnx {Scheme Procedure} locale-negative-separated-by-space? intl? [locale]
These procedures return a boolean indicating whether the currency
symbol should precede a positive/negative number, and whether a
whitespace should be inserted between the currency symbol and a
positive/negative amount.
@end deffn

@deffn {Scheme Procedure} locale-monetary-positive-sign [locale]
@deffnx {Scheme Procedure} locale-monetary-negative-sign [locale]
Return a string denoting the positive (respectively negative) sign
that should be used when printing a monetary amount.
@end deffn

@deffn {Scheme Procedure} locale-positive-sign-position
@deffnx {Scheme Procedure} locale-negative-sign-position
These functions return a symbol telling where a sign of a
positive/negative monetary amount is to appear when printing it.  The
possible values are:

@table @code
@item parenthesize
The currency symbol and quantity should be surrounded by parentheses.
@item sign-before
Print the sign string before the quantity and currency symbol.
@item sign-after
Print the sign string after the quantity and currency symbol.
@item sign-before-currency-symbol
Print the sign string right before the currency symbol.
@item sign-after-currency-symbol
Print the sign string right after the currency symbol.
@item unspecified
Unspecified.  We recommend you print the sign after the currency
symbol.
@end table

@end deffn

Finally, the two following procedures may be helpful when programming
user interfaces:

@deffn {Scheme Procedure} locale-yes-regexp [locale]
@deffnx {Scheme Procedure} locale-no-regexp [locale]
Return a string that can be used as a regular expression to recognize
a positive (respectively, negative) response to a yes/no question.
For the C locale, the default values are typically @code{"^[yY]"} and
@code{"^[nN]"}, respectively.

Here is an example:

@example
(use-modules (ice-9 rdelim))
(format #t "Does Guile rock?~%")
(let lp ((answer (read-line)))
  (cond ((string-match (locale-yes-regexp) answer)
         (format #t "High fives!~%"))
        ((string-match (locale-no-regexp) answer)
         (format #t "How about now? Does it rock yet?~%")
         (lp (read-line)))
        (else
         (format #t "What do you mean?~%")
         (lp (read-line)))))
@end example

For an internationalized yes/no string output, @code{gettext} should
be used (@pxref{Gettext Support}).
@end deffn

Example uses of some of these functions are the implementation of the
@code{number->locale-string} and @code{monetary-amount->locale-string}
procedures (@pxref{Number Input and Output}), as well as that the
SRFI-19 date and time conversion to/from strings (@pxref{SRFI-19}).

@node Gettext Support,  , Accessing Locale Information, Internationalization
@subsection Gettext Support

Guile provides an interface to GNU @code{gettext} for translating
message strings (@pxref{Introduction,,, gettext, GNU @code{gettext}
utilities}).

Messages are collected in domains, so different libraries and programs
maintain different message catalogues.  The @var{domain} parameter in
the functions below is a string (it becomes part of the message
catalog filename).

When @code{gettext} is not available, or if Guile was configured
@samp{--without-nls}, dummy functions doing no translation are
provided.  When @code{gettext} support is available in Guile, the
@code{i18n} feature is provided (@pxref{Feature Tracking}).

@deffn {Scheme Procedure} gettext msg [domain [category]]
@deffnx {C Function} scm_gettext (msg, domain, category)
Return the translation of @var{msg} in @var{domain}.  @var{domain} is
optional and defaults to the domain set through @code{textdomain}
below.  @var{category} is optional and defaults to @code{LC_MESSAGES}
(@pxref{Locales}).

Normal usage is for @var{msg} to be a literal string.
@command{xgettext} can extract those from the source to form a message
catalogue ready for translators (@pxref{xgettext Invocation,, Invoking
the @command{xgettext} Program, gettext, GNU @code{gettext}
utilities}).

@example
(display (gettext "You are in a maze of twisty passages."))
@end example

@code{_} is a commonly used shorthand, an application can make that an
alias for @code{gettext}.  Or a library can make a definition that
uses its specific @var{domain} (so an application can change the
default without affecting the library).

@example
(define (_ msg) (gettext msg "mylibrary"))
(display (_ "File not found."))
@end example

@code{_} is also a good place to perhaps strip disambiguating extra
text from the message string, as for instance in @ref{GUI program
problems,, How to use @code{gettext} in GUI programs, gettext, GNU
@code{gettext} utilities}.
@end deffn

@deffn {Scheme Procedure} ngettext msg msgplural n [domain [category]]
@deffnx {C Function} scm_ngettext (msg, msgplural, n, domain, category)
Return the translation of @var{msg}/@var{msgplural} in @var{domain},
with a plural form chosen appropriately for the number @var{n}.
@var{domain} is optional and defaults to the domain set through
@code{textdomain} below.  @var{category} is optional and defaults to
@code{LC_MESSAGES} (@pxref{Locales}).

@var{msg} is the singular form, and @var{msgplural} the plural.  When
no translation is available, @var{msg} is used if @math{@var{n} = 1},
or @var{msgplural} otherwise.  When translated, the message catalogue
can have a different rule, and can have more than two possible forms.

As per @code{gettext} above, normal usage is for @var{msg} and
@var{msgplural} to be literal strings, since @command{xgettext} can
extract them from the source to build a message catalogue.  For
example,

@example
(define (done n)
  (format #t (ngettext "~a file processed\n"
                       "~a files processed\n" n)
             n))

(done 1) @print{} 1 file processed
(done 3) @print{} 3 files processed
@end example

It's important to use @code{ngettext} rather than plain @code{gettext}
for plurals, since the rules for singular and plural forms in English
are not the same in other languages.  Only @code{ngettext} will allow
translators to give correct forms (@pxref{Plural forms,, Additional
functions for plural forms, gettext, GNU @code{gettext} utilities}).
@end deffn

@deffn {Scheme Procedure} textdomain [domain]
@deffnx {C Function} scm_textdomain (domain)
Get or set the default gettext domain.  When called with no parameter
the current domain is returned.  When called with a parameter,
@var{domain} is set as the current domain, and that new value
returned.  For example,

@example
(textdomain "myprog")
@result{} "myprog"
@end example
@end deffn

@deffn {Scheme Procedure} bindtextdomain domain [directory]
@deffnx {C Function} scm_bindtextdomain (domain, directory)
Get or set the directory under which to find message files for
@var{domain}.  When called without a @var{directory} the current
setting is returned.  When called with a @var{directory},
@var{directory} is set for @var{domain} and that new setting returned.
For example,

@example
(bindtextdomain "myprog" "/my/tree/share/locale")
@result{} "/my/tree/share/locale"
@end example

When using Autoconf/Automake, an application should arrange for the
configured @code{localedir} to get into the program (by substituting,
or by generating a config file) and set that for its domain.  This
ensures the catalogue can be found even when installed in a
non-standard location.
@end deffn

@deffn {Scheme Procedure} bind-textdomain-codeset domain [encoding]
@deffnx {C Function} scm_bind_textdomain_codeset (domain, encoding)
Get or set the text encoding to be used by @code{gettext} for messages
from @var{domain}.  @var{encoding} is a string, the name of a coding
system, for instance @nicode{"8859_1"}.  (On a Unix/POSIX system the
@command{iconv} program can list all available encodings.)

When called without an @var{encoding} the current setting is returned,
or @code{#f} if none yet set.  When called with an @var{encoding}, it
is set for @var{domain} and that new setting returned.  For example,

@example
(bind-textdomain-codeset "myprog")
@result{} #f
(bind-textdomain-codeset "myprog" "latin-9")
@result{} "latin-9"
@end example

The encoding requested can be different from the translated data file,
messages will be recoded as necessary.  But note that when there is no
translation, @code{gettext} returns its @var{msg} unchanged, ie.@:
without any recoding.  For that reason source message strings are best
as plain ASCII.

Currently Guile has no understanding of multi-byte characters, and
string functions won't recognise character boundaries in multi-byte
strings.  An application will at least be able to pass such strings
through to some output though.  Perhaps this will change in the
future.
@end deffn

@c Local Variables:
@c TeX-master: "guile.texi"
@c ispell-local-dictionary: "american"
@c End:

license: mit


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Initialization
@section Initializing Guile
@cindex Initializing Guile

Each thread that wants to use functions from the Guile API needs to
put itself into guile mode with either @code{scm_with_guile} or
@code{scm_init_guile}.  The global state of Guile is initialized
automatically when the first thread enters guile mode.

When a thread wants to block outside of a Guile API function, it
should leave guile mode temporarily with @code{scm_without_guile},
@xref{Blocking}.

Threads that are created by @code{call-with-new-thread} or
@code{scm_spawn_thread} start out in guile mode so you don't need to
initialize them.

@deftypefn {C Function} {void *} scm_with_guile (void *(*func)(void *), void *data)
Call @var{func}, passing it @var{data} and return what @var{func}
returns.  While @var{func} is running, the current thread is in guile
mode and can thus use the Guile API.

When @code{scm_with_guile} is called from guile mode, the thread remains
in guile mode when @code{scm_with_guile} returns.

Otherwise, it puts the current thread into guile mode and, if needed,
gives it a Scheme representation that is contained in the list returned
by @code{all-threads}, for example.  This Scheme representation is not
removed when @code{scm_with_guile} returns so that a given thread is
always represented by the same Scheme value during its lifetime, if at
all.

When this is the first thread that enters guile mode, the global state
of Guile is initialized before calling @code{func}.

The function @var{func} is called via
@code{scm_with_continuation_barrier}; thus, @code{scm_with_guile}
returns exactly once.

When @code{scm_with_guile} returns, the thread is no longer in guile
mode (except when @code{scm_with_guile} was called from guile mode, see
above).  Thus, only @code{func} can store @code{SCM} variables on the
stack and be sure that they are protected from the garbage collector.
See @code{scm_init_guile} for another approach at initializing Guile
that does not have this restriction.

It is OK to call @code{scm_with_guile} while a thread has temporarily
left guile mode via @code{scm_without_guile}.  It will then simply
temporarily enter guile mode again.
@end deftypefn

@deftypefn {C Function} void scm_init_guile ()
Arrange things so that all of the code in the current thread executes as
if from within a call to @code{scm_with_guile}.  That is, all functions
called by the current thread can assume that @code{SCM} values on their
stack frames are protected from the garbage collector (except when the
thread has explicitly left guile mode, of course).

When @code{scm_init_guile} is called from a thread that already has been
in guile mode once, nothing happens.  This behavior matters when you
call @code{scm_init_guile} while the thread has only temporarily left
guile mode: in that case the thread will not be in guile mode after
@code{scm_init_guile} returns.  Thus, you should not use
@code{scm_init_guile} in such a scenario.

When a uncaught throw happens in a thread that has been put into guile
mode via @code{scm_init_guile}, a short message is printed to the
current error port and the thread is exited via @code{scm_pthread_exit
(NULL)}.  No restrictions are placed on continuations.

The function @code{scm_init_guile} might not be available on all
platforms since it requires some stack-bounds-finding magic that might
not have been ported to all platforms that Guile runs on.  Thus, if you
can, it is better to use @code{scm_with_guile} or its variation
@code{scm_boot_guile} instead of this function.
@end deftypefn

@deftypefn {C Function} void scm_boot_guile (int @var{argc}, char **@var{argv}, void (*@var{main_func}) (void *@var{data}, int @var{argc}, char **@var{argv}), void *@var{data})
Enter guile mode as with @code{scm_with_guile} and call @var{main_func},
passing it @var{data}, @var{argc}, and @var{argv} as indicated.  When
@var{main_func} returns, @code{scm_boot_guile} calls @code{exit (0)};
@code{scm_boot_guile} never returns.  If you want some other exit value,
have @var{main_func} call @code{exit} itself.  If you don't want to exit
at all, use @code{scm_with_guile} instead of @code{scm_boot_guile}.

The function @code{scm_boot_guile} arranges for the Scheme
@code{command-line} function to return the strings given by @var{argc}
and @var{argv}.  If @var{main_func} modifies @var{argc} or @var{argv},
it should call @code{scm_set_program_arguments} with the final list, so
Scheme code will know which arguments have been processed
(@pxref{Runtime Environment}).
@end deftypefn

@deftypefn {C Function} void scm_shell (int @var{argc}, char **@var{argv})
Process command-line arguments in the manner of the @code{guile}
executable.  This includes loading the normal Guile initialization
files, interacting with the user or running any scripts or expressions
specified by @code{-s} or @code{-e} options, and then exiting.
@xref{Invoking Guile}, for more details.

Since this function does not return, you must do all
application-specific initialization before calling this function.
@end deftypefn