2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2008,
4 @c 2009, 2010, 2011 Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
7 @node Foreign Function Interface
8 @section Foreign Function Interface
9 @cindex foreign function interface
12 The more one hacks in Scheme, the more one realizes that there are
13 actually two computational worlds: one which is warm and alive, that
14 land of parentheses, and one cold and dead, the land of C and its ilk.
16 But yet we as programmers live in both worlds, and Guile itself is half
17 implemented in C. So it is that Guile's living half pays respect to its
18 dead counterpart, via a spectrum of interfaces to C ranging from dynamic
19 loading of Scheme primitives to dynamic binding of stock C library
23 * Foreign Libraries:: Dynamically linking to libraries.
24 * Foreign Functions:: Simple calls to C procedures.
25 * C Extensions:: Extending Guile in C with loadable modules.
26 * Modules and Extensions:: Loading C extensions into modules.
27 * Foreign Pointers:: Accessing global variables.
28 * Dynamic FFI:: Calling arbitrary C functions.
32 @node Foreign Libraries
33 @subsection Foreign Libraries
35 Most modern Unices have something called @dfn{shared libraries}. This
36 ordinarily means that they have the capability to share the executable
37 image of a library between several running programs to save memory and
38 disk space. But generally, shared libraries give a lot of additional
39 flexibility compared to the traditional static libraries. In fact,
40 calling them `dynamic' libraries is as correct as calling them `shared'.
42 Shared libraries really give you a lot of flexibility in addition to the
43 memory and disk space savings. When you link a program against a shared
44 library, that library is not closely incorporated into the final
45 executable. Instead, the executable of your program only contains
46 enough information to find the needed shared libraries when the program
47 is actually run. Only then, when the program is starting, is the final
48 step of the linking process performed. This means that you need not
49 recompile all programs when you install a new, only slightly modified
50 version of a shared library. The programs will pick up the changes
51 automatically the next time they are run.
53 Now, when all the necessary machinery is there to perform part of the
54 linking at run-time, why not take the next step and allow the programmer
55 to explicitly take advantage of it from within his program? Of course,
56 many operating systems that support shared libraries do just that, and
57 chances are that Guile will allow you to access this feature from within
58 your Scheme programs. As you might have guessed already, this feature
59 is called @dfn{dynamic linking}.@footnote{Some people also refer to the
60 final linking stage at program startup as `dynamic linking', so if you
61 want to make yourself perfectly clear, it is probably best to use the
62 more technical term @dfn{dlopening}, as suggested by Gordon Matzigkeit
63 in his libtool documentation.}
65 We titled this section ``foreign libraries'' because although the name
66 ``foreign'' doesn't leak into the API, the world of C really is foreign
67 to Scheme -- and that estrangement extends to components of foreign
68 libraries as well, as we see in future sections.
70 @deffn {Scheme Procedure} dynamic-link [library]
71 @deffnx {C Function} scm_dynamic_link (library)
72 Find the shared library denoted by @var{library} (a string) and link it
73 into the running Guile application. When everything works out, return a
74 Scheme object suitable for representing the linked object file.
75 Otherwise an error is thrown. How object files are searched is system
78 Normally, @var{library} is just the name of some shared library file
79 that will be searched for in the places where shared libraries usually
80 reside, such as in @file{/usr/lib} and @file{/usr/local/lib}.
82 @var{library} should not contain an extension such as @code{.so}. The
83 correct file name extension for the host operating system is provided
84 automatically, according to libltdl's rules (@pxref{Libltdl interface,
85 lt_dlopenext, @code{lt_dlopenext}, libtool, Shared Library Support for
88 When @var{library} is omitted, a @dfn{global symbol handle} is returned. This
89 handle provides access to the symbols available to the program at run-time,
90 including those exported by the program itself and the shared libraries already
94 @deffn {Scheme Procedure} dynamic-object? obj
95 @deffnx {C Function} scm_dynamic_object_p (obj)
96 Return @code{#t} if @var{obj} is a dynamic library handle, or @code{#f}
100 @deffn {Scheme Procedure} dynamic-unlink dobj
101 @deffnx {C Function} scm_dynamic_unlink (dobj)
102 Unlink the indicated object file from the application. The
103 argument @var{dobj} must have been obtained by a call to
104 @code{dynamic-link}. After @code{dynamic-unlink} has been
105 called on @var{dobj}, its content is no longer accessible.
109 (define libgl-obj (dynamic-link "libGL"))
111 @result{} #<dynamic-object "libGL">
112 (dynamic-unlink libGL-obj)
114 @result{} #<dynamic-object "libGL" (unlinked)>
117 As you can see, after calling @code{dynamic-unlink} on a dynamically
118 linked library, it is marked as @samp{(unlinked)} and you are no longer
119 able to use it with @code{dynamic-call}, etc. Whether the library is
120 really removed from you program is system-dependent and will generally
121 not happen when some other parts of your program still use it.
123 When dynamic linking is disabled or not supported on your system,
124 the above functions throw errors, but they are still available.
127 @node Foreign Functions
128 @subsection Foreign Functions
130 The most natural thing to do with a dynamic library is to grovel around
131 in it for a function pointer: a @dfn{foreign function}.
132 @code{dynamic-func} exists for that purpose.
134 @deffn {Scheme Procedure} dynamic-func name dobj
135 @deffnx {C Function} scm_dynamic_func (name, dobj)
136 Return a ``handle'' for the func @var{name} in the shared object referred to
137 by @var{dobj}. The handle can be passed to @code{dynamic-call} to
138 actually call the function.
140 Regardless whether your C compiler prepends an underscore @samp{_} to the global
141 names in a program, you should @strong{not} include this underscore in
142 @var{name} since it will be added automatically when necessary.
145 Guile has static support for calling functions with no arguments,
148 @deffn {Scheme Procedure} dynamic-call func dobj
149 @deffnx {C Function} scm_dynamic_call (func, dobj)
150 Call the C function indicated by @var{func} and @var{dobj}.
151 The function is passed no arguments and its return value is
152 ignored. When @var{function} is something returned by
153 @code{dynamic-func}, call that function and ignore @var{dobj}.
154 When @var{func} is a string , look it up in @var{dynobj}; this
157 (dynamic-call (dynamic-func @var{func} @var{dobj}) #f)
160 Interrupts are deferred while the C function is executing (with
161 @code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}).
164 @code{dynamic-call} is not very powerful. It is mostly intended to be
165 used for calling specially written initialization functions that will
166 then add new primitives to Guile. For example, we do not expect that you
167 will dynamically link @file{libX11} with @code{dynamic-link} and then
168 construct a beautiful graphical user interface just by using
169 @code{dynamic-call}. Instead, the usual way would be to write a special
170 Guile-to-X11 glue library that has intimate knowledge about both Guile
171 and X11 and does whatever is necessary to make them inter-operate
172 smoothly. This glue library could then be dynamically linked into a
173 vanilla Guile interpreter and activated by calling its initialization
174 function. That function would add all the new types and primitives to
175 the Guile interpreter that it has to offer.
177 (There is actually another, better option: simply to create a
178 @file{libX11} wrapper in Scheme via the dynamic FFI. @xref{Dynamic FFI},
179 for more information.)
181 Given some set of C extensions to Guile, the next logical step is to
182 integrate these glue libraries into the module system of Guile so that
183 you can load new primitives into a running system just as you can load
186 @deffn {Scheme Procedure} load-extension lib init
187 @deffnx {C Function} scm_load_extension (lib, init)
188 Load and initialize the extension designated by LIB and INIT.
189 When there is no pre-registered function for LIB/INIT, this is
193 (dynamic-call INIT (dynamic-link LIB))
196 When there is a pre-registered function, that function is called
199 Normally, there is no pre-registered function. This option exists
200 only for situations where dynamic linking is unavailable or unwanted.
201 In that case, you would statically link your program with the desired
202 library, and register its init function right after Guile has been
205 As for @code{dynamic-link}, @var{lib} should not contain any suffix such
206 as @code{.so} (@pxref{Foreign Libraries, dynamic-link}). It
207 should also not contain any directory components. Libraries that
208 implement Guile Extensions should be put into the normal locations for
209 shared libraries. We recommend to use the naming convention
210 @file{libguile-bla-blum} for a extension related to a module @code{(bla
213 The normal way for a extension to be used is to write a small Scheme
214 file that defines a module, and to load the extension into this
215 module. When the module is auto-loaded, the extension is loaded as
219 (define-module (bla blum))
221 (load-extension "libguile-bla-blum" "bla_init_blum")
226 @subsection C Extensions
228 The most interesting application of dynamically linked libraries is
229 probably to use them for providing @emph{compiled code modules} to
230 Scheme programs. As much fun as programming in Scheme is, every now and
231 then comes the need to write some low-level C stuff to make Scheme even
234 Not only can you put these new primitives into their own module (see the
235 previous section), you can even put them into a shared library that is
236 only then linked to your running Guile image when it is actually
239 An example will hopefully make everything clear. Suppose we want to
240 make the Bessel functions of the C library available to Scheme in the
241 module @samp{(math bessel)}. First we need to write the appropriate
242 glue code to convert the arguments and return values of the functions
243 from Scheme to C and back. Additionally, we need a function that will
244 add them to the set of Guile primitives. Because this is just an
245 example, we will only implement this for the @code{j0} function.
249 #include <libguile.h>
254 return scm_from_double (j0 (scm_to_double (x, "j0")));
260 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
264 We can already try to bring this into action by manually calling the low
265 level functions for performing dynamic linking. The C source file needs
266 to be compiled into a shared library. Here is how to do it on
267 GNU/Linux, please refer to the @code{libtool} documentation for how to
268 create dynamically linkable libraries portably.
271 gcc -shared -o libbessel.so -fPIC bessel.c
277 (define bessel-lib (dynamic-link "./libbessel.so"))
278 (dynamic-call "init_math_bessel" bessel-lib)
280 @result{} 0.223890779141236
283 The filename @file{./libbessel.so} should be pointing to the shared
284 library produced with the @code{gcc} command above, of course. The
285 second line of the Guile interaction will call the
286 @code{init_math_bessel} function which in turn will register the C
287 function @code{j0_wrapper} with the Guile interpreter under the name
288 @code{j0}. This function becomes immediately available and we can call
291 Fun, isn't it? But we are only half way there. This is what
292 @code{apropos} has to say about @code{j0}:
296 @print{} (guile-user): j0 #<primitive-procedure j0>
299 As you can see, @code{j0} is contained in the root module, where all
300 the other Guile primitives like @code{display}, etc live. In general,
301 a primitive is put into whatever module is the @dfn{current module} at
302 the time @code{scm_c_define_gsubr} is called.
304 A compiled module should have a specially named @dfn{module init
305 function}. Guile knows about this special name and will call that
306 function automatically after having linked in the shared library. For
307 our example, we replace @code{init_math_bessel} with the following code in
312 init_math_bessel (void *unused)
314 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
315 scm_c_export ("j0", NULL);
319 scm_init_math_bessel_module ()
321 scm_c_define_module ("math bessel", init_math_bessel, NULL);
325 The general pattern for the name of a module init function is:
326 @samp{scm_init_}, followed by the name of the module where the
327 individual hierarchical components are concatenated with underscores,
328 followed by @samp{_module}.
330 After @file{libbessel.so} has been rebuilt, we need to place the shared
331 library into the right place.
333 Once the module has been correctly installed, it should be possible to
337 guile> (load-extension "./libbessel.so" "scm_init_math_bessel_module")
338 guile> (use-modules (math bessel))
341 guile> (apropos "j0")
342 @print{} (math bessel): j0 #<primitive-procedure j0>
348 @node Modules and Extensions
349 @subsection Modules and Extensions
351 The new primitives that you add to Guile with @code{scm_c_define_gsubr}
352 (@pxref{Primitive Procedures}) or with any of the other mechanisms are
353 placed into the module that is current when the
354 @code{scm_c_define_gsubr} is executed. Extensions loaded from the REPL,
355 for example, will be placed into the @code{(guile-user)} module, if the
356 REPL module was not changed.
358 To define C primitives within a specific module, the simplest way is:
361 (define-module (foo bar))
362 (load-extension "foobar-c-code" "foo_bar_init")
366 When loaded with @code{(use-modules (foo bar))}, the
367 @code{load-extension} call looks for the @file{foobar-c-code.so} (etc)
368 object file in Guile's @code{extensiondir}, which is usually a
369 subdirectory of the @code{libdir}. For example, if your libdir is
370 @file{/usr/lib}, the @code{extensiondir} for the Guile @value{EFFECTIVE-VERSION}.@var{x}
371 series will be @file{/usr/lib/guile/@value{EFFECTIVE-VERSION}/}.
373 The extension path includes the major and minor version of Guile (the
374 ``effective version''), because Guile guarantees compatibility within a
375 given effective version. This allows you to install different versions
376 of the same extension for different versions of Guile.
378 If the extension is not found in the @code{extensiondir}, Guile will
379 also search the standard system locations, such as @file{/usr/lib} or
380 @file{/usr/local/lib}. It is preferable, however, to keep your extension
381 out of the system library path, to prevent unintended interference with
382 other dynamically-linked C libraries.
384 If someone installs your module to a non-standard location then the
385 object file won't be found. You can address this by inserting the
386 install location in the @file{foo/bar.scm} file. This is convenient
387 for the user and also guarantees the intended object is read, even if
388 stray older or newer versions are in the loader's path.
390 The usual way to specify an install location is with a @code{prefix}
391 at the configure stage, for instance @samp{./configure prefix=/opt}
392 results in library files as say @file{/opt/lib/foobar-c-code.so}.
393 When using Autoconf (@pxref{Top, , Introduction, autoconf, The GNU
394 Autoconf Manual}), the library location is in a @code{libdir}
395 variable. Its value is intended to be expanded by @command{make}, and
396 can by substituted into a source file like @file{foo.scm.in}
399 (define-module (foo bar))
400 (load-extension "XXextensiondirXX/foobar-c-code" "foo_bar_init")
404 with the following in a @file{Makefile}, using @command{sed}
405 (@pxref{Top, , Introduction, sed, SED, A Stream Editor}),
409 sed 's|XXextensiondirXX|$(libdir)/guile/@value{EFFECTIVE-VERSION}|' <foo.scm.in >foo.scm
412 The actual pattern @code{XXextensiondirXX} is arbitrary, it's only something
413 which doesn't otherwise occur. If several modules need the value, it
414 can be easier to create one @file{foo/config.scm} with a define of the
415 @code{extensiondir} location, and use that as required.
418 (define-module (foo config))
419 (define-public foo-config-extensiondir "XXextensiondirXX"")
422 Such a file might have other locations too, for instance a data
423 directory for auxiliary files, or @code{localedir} if the module has
424 its own @code{gettext} message catalogue
425 (@pxref{Internationalization}).
427 It will be noted all of the above requires that the Scheme code to be
428 found in @code{%load-path} (@pxref{Build Config}). Presently it's
429 left up to the system administrator or each user to augment that path
430 when installing Guile modules in non-default locations. But having
431 reached the Scheme code, that code should take care of hitting any of
432 its own private files etc.
435 @node Foreign Pointers
436 @subsection Foreign Pointers
438 The previous sections have shown how Guile can be extended at runtime by
439 loading compiled C extensions. This approach is all well and good, but
440 wouldn't it be nice if we didn't have to write any C at all? This
441 section takes up the problem of accessing C values from Scheme, and the
442 next discusses C functions.
445 * Foreign Types:: Expressing C types in Scheme.
446 * Foreign Variables:: Pointers to C symbols.
447 * Void Pointers and Byte Access:: Pointers into the ether.
448 * Foreign Structs:: Packing and unpacking structs.
452 @subsubsection Foreign Types
454 The first impedance mismatch that one sees between C and Scheme is that
455 in C, the storage locations (variables) are typed, but in Scheme types
456 are associated with values, not variables. @xref{Values and Variables}.
458 So when describing a C function or a C structure so that it can be
459 accessed from Scheme, the data types of the parameters or fields must be
462 These ``C type values'' may be constructed using the constants and
463 procedures from the @code{(system foreign)} module, which may be loaded
467 (use-modules (system foreign))
470 @code{(system foreign)} exports a number of values expressing the basic
473 @defvr {Scheme Variable} int8
474 @defvrx {Scheme Variable} uint8
475 @defvrx {Scheme Variable} uint16
476 @defvrx {Scheme Variable} int16
477 @defvrx {Scheme Variable} uint32
478 @defvrx {Scheme Variable} int32
479 @defvrx {Scheme Variable} uint64
480 @defvrx {Scheme Variable} int64
481 @defvrx {Scheme Variable} float
482 @defvrx {Scheme Variable} double
483 These values represent the C numeric types of the specified sizes and
487 In addition there are some convenience bindings for indicating types of
488 platform-dependent size:
490 @defvr {Scheme Variable} int
491 @defvrx {Scheme Variable} unsigned-int
492 @defvrx {Scheme Variable} long
493 @defvrx {Scheme Variable} unsigned-long
494 @defvrx {Scheme Variable} size_t
495 Values exported by the @code{(system foreign)} module, representing C
496 numeric types. For example, @code{long} may be @code{equal?} to
497 @code{int64} on a 64-bit platform.
500 @defvr {Scheme Variable} void
501 The @code{void} type. It can be used as the first argument to
502 @code{pointer->procedure} to wrap a C function that returns nothing.
505 In addition, the symbol @code{*} is used by convention to denote pointer
506 types. Procedures detailed in the following sections, such as
507 @code{pointer->procedure}, accept it as a type descriptor.
509 @node Foreign Variables
510 @subsubsection Foreign Variables
512 Pointers to variables in the current address space may be looked up
513 dynamically using @code{dynamic-pointer}.
515 @deffn {Scheme Procedure} dynamic-pointer name dobj
516 @deffnx {C Function} scm_dynamic_pointer (name, dobj)
517 Return a ``wrapped pointer'' for the symbol @var{name} in the shared
518 object referred to by @var{dobj}. The returned pointer points to a C
521 Regardless whether your C compiler prepends an underscore @samp{_} to the global
522 names in a program, you should @strong{not} include this underscore in
523 @var{name} since it will be added automatically when necessary.
526 For example, currently Guile has a variable, @code{scm_numptob}, as part
527 of its API. It is declared as a C @code{long}. So, to create a handle
528 pointing to that foreign value, we do:
531 (use-modules (system foreign))
532 (define numptob (dynamic-pointer "scm_numptob" (dynamic-link)))
534 @result{} #<pointer 0x7fb35b1b4688>
537 (The next section discusses ways to dereference pointers.)
539 A value returned by @code{dynamic-pointer} is a Scheme wrapper for a C
542 @deffn {Scheme Procedure} pointer-address pointer
543 @deffnx {C Function} scm_pointer_address pointer
544 Return the numerical value of @var{pointer}.
547 (pointer-address numptob)
548 @result{} 139984413364296 ; YMMV
552 @deffn {Scheme Procedure} make-pointer address [finalizer]
553 Return a foreign pointer object pointing to @var{address}. If
554 @var{finalizer} is passed, it should be a pointer to a one-argument C
555 function that will be called when the pointer object becomes
559 @deffn {Scheme Procedure} pointer? obj
560 Return @code{#t} if @var{obj} is a pointer object, @code{#f} otherwise.
563 @defvr {Scheme Variable} %null-pointer
564 A foreign pointer whose value is 0.
567 @deffn {Scheme Procedure} null-pointer? pointer
568 Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
571 For the purpose of passing SCM values directly to foreign functions, and
572 allowing them to return SCM values, Guile also supports some unsafe
575 @deffn {Scheme Procedure} scm->pointer scm
576 Return a foreign pointer object with the @code{object-address}
580 @deffn {Scheme Procedure} pointer->scm pointer
581 Unsafely cast @var{pointer} to a Scheme object.
586 @node Void Pointers and Byte Access
587 @subsubsection Void Pointers and Byte Access
589 Wrapped pointers are untyped, so they are essentially equivalent to C
590 @code{void} pointers. As in C, the memory region pointed to by a
591 pointer can be accessed at the byte level. This is achieved using
592 @emph{bytevectors} (@pxref{Bytevectors}). The @code{(rnrs bytevector)}
593 module contains procedures that can be used to convert byte sequences to
594 Scheme objects such as strings, floating point numbers, or integers.
596 @deffn {Scheme Procedure} pointer->bytevector pointer len [offset [uvec_type]]
597 @deffnx {C Function} scm_foreign_to_bytevector pointer len offset uvec_type
598 Return a bytevector aliasing the @var{len} bytes pointed to by
601 The user may specify an alternate default interpretation for
602 the memory by passing the @var{uvec_type} argument, to indicate
603 that the memory is an array of elements of that type.
604 @var{uvec_type} should be something that
605 @code{uniform-vector-element-type} would return, like @code{f32}
608 When @var{offset} is passed, it specifies the offset in bytes relative
609 to @var{pointer} of the memory region aliased by the returned
612 Mutating the returned bytevector mutates the memory pointed to by
613 @var{pointer}, so buckle your seatbelts.
616 @deffn {Scheme Procedure} bytevector->pointer bv [offset]
617 @deffnx {C Function} scm_bytevector_to_pointer bv offset
618 Return a pointer pointer aliasing the memory pointed to by @var{bv} or
619 @var{offset} bytes after @var{bv} when @var{offset} is passed.
622 In addition to these primitives, convenience procedures are available:
624 @deffn {Scheme Procedure} dereference-pointer pointer
625 Assuming @var{pointer} points to a memory region that holds a pointer,
629 @deffn {Scheme Procedure} string->pointer string
630 Return a foreign pointer to a nul-terminated copy of @var{string} in the
631 current locale encoding. The C string is freed when the returned
632 foreign pointer becomes unreachable.
634 This is the Scheme equivalent of @code{scm_to_locale_string}.
637 @deffn {Scheme Procedure} pointer->string pointer
638 Return the string representing the C nul-terminated string
639 pointed to by @var{pointer}. The C string is assumed to be
640 in the current locale encoding.
642 This is the Scheme equivalent of @code{scm_from_locale_string}.
645 @cindex wrapped pointer types
646 Most object-oriented C libraries use pointers to specific data
647 structures to identify objects. It is useful in such cases to reify the
648 different pointer types as disjoint Scheme types. The
649 @code{define-wrapped-pointer-type} macro simplifies this.
651 @deffn {Scheme Syntax} define-wrapped-pointer-type type-name pred wrap unwrap print
652 Define helper procedures to wrap pointer objects into Scheme objects
653 with a disjoint type. Specifically, this macro defines:
656 @item @var{pred}, a predicate for the new Scheme type;
657 @item @var{wrap}, a procedure that takes a pointer object and returns an
658 object that satisfies @var{pred};
659 @item @var{unwrap}, which does the reverse.
662 @var{wrap} preserves pointer identity, for two pointer objects @var{p1}
663 and @var{p2} that are @code{equal?}, @code{(eq? (@var{wrap} @var{p1})
664 (@var{wrap} @var{p2})) @result{} #t}.
666 Finally, @var{print} should name a user-defined procedure to print such
667 objects. The procedure is passed the wrapped object and a port to write
670 For example, assume we are wrapping a C library that defines a type,
671 @code{bottle_t}, and functions that can be passed @code{bottle_t *}
672 pointers to manipulate them. We could write:
675 (define-wrapped-pointer-type bottle
677 wrap-bottle unwrap-bottle
679 (format p "#<bottle of ~a ~x>"
681 (pointer-address (unwrap-foo b)))))
684 ;; Wrapper for `bottle_t *grab (void)'.
685 (let ((grab (pointer->procedure '*
686 (dynamic-func "grab_bottle" libbottle)
689 "Return a new bottle."
690 (wrap-bottle (grab)))))
692 (define bottle-contents
693 ;; Wrapper for `const char *bottle_contents (bottle_t *)'.
694 (let ((contents (pointer->procedure '*
695 (dynamic-func "bottle_contents"
699 "Return the contents of B."
700 (pointer->string (contents (unwrap-bottle b))))))
702 (write (grab-bottle))
703 @result{} #<bottle of Ch@^ateau Haut-Brion 803d36>
706 In this example, @code{grab-bottle} is guaranteed to return a genuine
707 @code{bottle} object satisfying @code{bottle?}. Likewise,
708 @code{bottle-contents} errors out when its argument is not a genuine
709 @code{bottle} object.
712 Going back to the @code{scm_numptob} example above, here is how we can
713 read its value as a C @code{long} integer:
716 (use-modules (rnrs bytevectors))
718 (bytevector-uint-ref (pointer->bytevector numptob (sizeof long))
719 0 (native-endianness)
724 If we wanted to corrupt Guile's internal state, we could set
725 @code{scm_numptob} to another value; but we shouldn't, because that
726 variable is not meant to be set. Indeed this point applies more widely:
727 the C API is a dangerous place to be. Not only might setting a value
728 crash your program, simply accessing the data pointed to by a dangling
729 pointer or similar can prove equally disastrous.
731 @node Foreign Structs
732 @subsubsection Foreign Structs
734 Finally, one last note on foreign values before moving on to actually
735 calling foreign functions. Sometimes you need to deal with C structs,
736 which requires interpreting each element of the struct according to the
737 its type, offset, and alignment. Guile has some primitives to support
740 @deffn {Scheme Procedure} sizeof type
741 @deffnx {C Function} scm_sizeof type
742 Return the size of @var{type}, in bytes.
744 @var{type} should be a valid C type, like @code{int}.
745 Alternately @var{type} may be the symbol @code{*}, in which
746 case the size of a pointer is returned. @var{type} may
747 also be a list of types, in which case the size of a
748 @code{struct} with ABI-conventional packing is returned.
751 @deffn {Scheme Procedure} alignof type
752 @deffnx {C Function} scm_alignof type
753 Return the alignment of @var{type}, in bytes.
755 @var{type} should be a valid C type, like @code{int}.
756 Alternately @var{type} may be the symbol @code{*}, in which
757 case the alignment of a pointer is returned. @var{type} may
758 also be a list of types, in which case the alignment of a
759 @code{struct} with ABI-conventional packing is returned.
762 Guile also provides some convenience methods to pack and unpack foreign
763 pointers wrapping C structs.
765 @deffn {Scheme Procedure} make-c-struct types vals
766 Create a foreign pointer to a C struct containing @var{vals} with types
769 @var{vals} and @code{types} should be lists of the same length.
772 @deffn {Scheme Procedure} parse-c-struct foreign types
773 Parse a foreign pointer to a C struct, returning a list of values.
775 @code{types} should be a list of C types.
778 For example, to create and parse the equivalent of a @code{struct @{
779 int64_t a; uint8_t b; @}}:
782 (parse-c-struct (make-c-struct (list int64 uint8)
788 As yet, Guile only has convenience routines to support
789 conventionally-packed structs. But given the @code{bytevector->foreign}
790 and @code{foreign->bytevector} routines, one can create and parse
791 tightly packed structs and unions by hand. See the code for
792 @code{(system foreign)} for details.
796 @subsection Dynamic FFI
798 Of course, the land of C is not all nouns and no verbs: there are
799 functions too, and Guile allows you to call them.
801 @deffn {Scheme Procedure} pointer->procedure return_type func_ptr arg_types
802 @deffnx {C Procedure} scm_pointer_to_procedure return_type func_ptr arg_types
803 Make a foreign function.
805 Given the foreign void pointer @var{func_ptr}, its argument and
806 return types @var{arg_types} and @var{return_type}, return a
807 procedure that will pass arguments to the foreign function
808 and return appropriate values.
810 @var{arg_types} should be a list of foreign types.
811 @code{return_type} should be a foreign type. @xref{Foreign Types}, for
812 more information on foreign types.
815 Here is a better definition of @code{(math bessel)}:
818 (define-module (math bessel)
819 #:use-module (system foreign)
822 (define libm (dynamic-link "libm"))
825 (pointer->procedure double
826 (dynamic-func "j0" libm)
830 That's it! No C at all.
832 Numeric arguments and return values from foreign functions are
833 represented as Scheme values. For example, @code{j0} in the above
834 example takes a Scheme number as its argument, and returns a Scheme
837 Pointers may be passed to and returned from foreign functions as well.
838 In that case the type of the argument or return value should be the
839 symbol @code{*}, indicating a pointer. For example, the following
840 code makes @code{memcpy} available to Scheme:
844 (let ((this (dynamic-link)))
845 (pointer->procedure '*
846 (dynamic-func "memcpy" this)
847 (list '* '* size_t))))
850 To invoke @code{memcpy}, one must pass it foreign pointers:
853 (use-modules (rnrs bytevectors))
856 (u8-list->bytevector '(0 1 2 3 4 5 6 7)))
858 (bytevector->pointer src-bits))
860 (bytevector->pointer (make-bytevector 16 0)))
862 (memcpy dest src (bytevector-length src-bits))
864 (bytevector->u8-list (pointer->bytevector dest 16))
865 @result{} (0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0)
868 One may also pass structs as values, passing structs as foreign
869 pointers. @xref{Foreign Structs}, for more information on how to express
870 struct types and struct values.
872 ``Out'' arguments are passed as foreign pointers. The memory pointed to
873 by the foreign pointer is mutated in place.
877 ;; time_t tv_sec; /* seconds */
878 ;; suseconds_t tv_usec; /* microseconds */
880 ;; assuming fields are of type "long"
883 (let ((f (pointer->procedure
885 (dynamic-func "gettimeofday" (dynamic-link))
887 (tv-type (list long long)))
889 (let* ((timeval (make-c-struct tv-type (list 0 0)))
890 (ret (f timeval %null-pointer)))
892 (apply values (parse-c-struct timeval tv-type))
893 (error "gettimeofday returned an error" ret))))))
900 As you can see, this interface to foreign functions is at a very low,
901 somewhat dangerous level@footnote{A contribution to Guile in the form of
902 a high-level FFI would be most welcome.}.
905 The FFI can also work in the opposite direction: making Scheme
906 procedures callable from C. This makes it possible to use Scheme
907 procedures as ``callbacks'' expected by C function.
909 @deffn {Scheme Procedure} procedure->pointer return-type proc arg-types
910 @deffnx {C Function} scm_procedure_to_pointer (return_type, proc, arg_types)
911 Return a pointer to a C function of type @var{return-type}
912 taking arguments of types @var{arg-types} (a list) and
913 behaving as a proxy to procedure @var{proc}. Thus
914 @var{proc}'s arity, supported argument types, and return
915 type should match @var{return-type} and @var{arg-types}.
918 As an example, here's how the C library's @code{qsort} array sorting
919 function can be made accessible to Scheme (@pxref{Array Sort Function,
920 @code{qsort},, libc, The GNU C Library Reference Manual}):
924 (let ((qsort (pointer->procedure void
925 (dynamic-func "qsort"
927 (list '* size_t size_t '*))))
929 ;; Sort bytevector BV in-place according to comparison
930 ;; procedure COMPARE.
931 (let ((ptr (procedure->pointer int
933 ;; X and Y are pointers so,
934 ;; for convenience, dereference
935 ;; them before calling COMPARE.
936 (compare (dereference-uint8* x)
937 (dereference-uint8* y)))
939 (qsort (bytevector->pointer bv)
940 (bytevector-length bv) 1 ;; we're sorting bytes
943 (define (dereference-uint8* ptr)
944 ;; Helper function: dereference the byte pointed to by PTR.
945 (let ((b (pointer->bytevector ptr 1)))
946 (bytevector-u8-ref b 0)))
949 ;; An unsorted array of bytes.
950 (u8-list->bytevector '(7 1 127 3 5 4 77 2 9 0)))
953 (qsort! bv (lambda (x y) (- x y)))
955 ;; Let's see what the sorted array looks like:
956 (bytevector->u8-list bv)
957 @result{} (0 1 2 3 4 5 7 9 77 127)
962 Note that @code{procedure->pointer} is not supported (and not defined)
963 on a few exotic architectures. Thus, user code may need to check
964 @code{(defined? 'procedure->pointer)}. Nevertheless, it is available on
965 many architectures, including (as of libffi 3.0.9) x86, ia64, SPARC,
966 PowerPC, ARM, and MIPS, to name a few.
969 @c TeX-master: "guile.texi"