Update the FFI doc.
[bpt/guile.git] / doc / ref / api-foreign.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2008, 2009, 2010
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node Foreign Function Interface
9 @section Foreign Function Interface
10 @cindex foreign function interface
11 @cindex ffi
12
13 The more one hacks in Scheme, the more one realizes that there are
14 actually two computational worlds: one which is warm and alive, that
15 land of parentheses, and one cold and dead, the land of C and its ilk.
16
17 But yet we as programmers live in both worlds, and Guile itself is half
18 implemented in C. So it is that Guile's living half pays respect to its
19 dead counterpart, via a spectrum of interfaces to C ranging from dynamic
20 loading of Scheme primitives to dynamic binding of stock C library
21 prodedures.
22
23 @menu
24 * Foreign Libraries:: Dynamically linking to libraries.
25 * Foreign Functions:: Simple calls to C procedures.
26 * C Extensions:: Extending Guile in C with loadable modules.
27 * Modules and Extensions:: Loading C extensions into modules.
28 * Foreign Pointers:: Accessing global variables.
29 * Dynamic FFI:: Calling arbitrary C functions.
30 @end menu
31
32
33 @node Foreign Libraries
34 @subsection Foreign Libraries
35
36 Most modern Unices have something called @dfn{shared libraries}. This
37 ordinarily means that they have the capability to share the executable
38 image of a library between several running programs to save memory and
39 disk space. But generally, shared libraries give a lot of additional
40 flexibility compared to the traditional static libraries. In fact,
41 calling them `dynamic' libraries is as correct as calling them `shared'.
42
43 Shared libraries really give you a lot of flexibility in addition to the
44 memory and disk space savings. When you link a program against a shared
45 library, that library is not closely incorporated into the final
46 executable. Instead, the executable of your program only contains
47 enough information to find the needed shared libraries when the program
48 is actually run. Only then, when the program is starting, is the final
49 step of the linking process performed. This means that you need not
50 recompile all programs when you install a new, only slightly modified
51 version of a shared library. The programs will pick up the changes
52 automatically the next time they are run.
53
54 Now, when all the necessary machinery is there to perform part of the
55 linking at run-time, why not take the next step and allow the programmer
56 to explicitly take advantage of it from within his program? Of course,
57 many operating systems that support shared libraries do just that, and
58 chances are that Guile will allow you to access this feature from within
59 your Scheme programs. As you might have guessed already, this feature
60 is called @dfn{dynamic linking}.@footnote{Some people also refer to the
61 final linking stage at program startup as `dynamic linking', so if you
62 want to make yourself perfectly clear, it is probably best to use the
63 more technical term @dfn{dlopening}, as suggested by Gordon Matzigkeit
64 in his libtool documentation.}
65
66 We titled this section ``foreign libraries'' because although the name
67 ``foreign'' doesn't leak into the API, the world of C really is foreign
68 to Scheme -- and that estrangement extends to components of foreign
69 libraries as well, as we see in future sections.
70
71 @deffn {Scheme Procedure} dynamic-link [library]
72 @deffnx {C Function} scm_dynamic_link (library)
73 Find the shared library denoted by @var{library} (a string) and link it
74 into the running Guile application. When everything works out, return a
75 Scheme object suitable for representing the linked object file.
76 Otherwise an error is thrown. How object files are searched is system
77 dependent.
78
79 Normally, @var{library} is just the name of some shared library file
80 that will be searched for in the places where shared libraries usually
81 reside, such as in @file{/usr/lib} and @file{/usr/local/lib}.
82
83 When @var{library} is omitted, a @dfn{global symbol handle} is returned. This
84 handle provides access to the symbols available to the program at run-time,
85 including those exported by the program itself and the shared libraries already
86 loaded.
87 @end deffn
88
89 @deffn {Scheme Procedure} dynamic-object? obj
90 @deffnx {C Function} scm_dynamic_object_p (obj)
91 Return @code{#t} if @var{obj} is a dynamic library handle, or @code{#f}
92 otherwise.
93 @end deffn
94
95 @deffn {Scheme Procedure} dynamic-unlink dobj
96 @deffnx {C Function} scm_dynamic_unlink (dobj)
97 Unlink the indicated object file from the application. The
98 argument @var{dobj} must have been obtained by a call to
99 @code{dynamic-link}. After @code{dynamic-unlink} has been
100 called on @var{dobj}, its content is no longer accessible.
101 @end deffn
102
103 @smallexample
104 (define libgl-obj (dynamic-link "libGL"))
105 libgl-obj
106 @result{} #<dynamic-object "libGL">
107 (dynamic-unlink libGL-obj)
108 libGL-obj
109 @result{} #<dynamic-object "libGL" (unlinked)>
110 @end smallexample
111
112 As you can see, after calling @code{dynamic-unlink} on a dynamically
113 linked library, it is marked as @samp{(unlinked)} and you are no longer
114 able to use it with @code{dynamic-call}, etc. Whether the library is
115 really removed from you program is system-dependent and will generally
116 not happen when some other parts of your program still use it.
117
118 When dynamic linking is disabled or not supported on your system,
119 the above functions throw errors, but they are still available.
120
121
122 @node Foreign Functions
123 @subsection Foreign Functions
124
125 The most natural thing to do with a dynamic library is to grovel around
126 in it for a function pointer: a @dfn{foreign function}.
127 @code{dynamic-func} exists for that purpose.
128
129 @deffn {Scheme Procedure} dynamic-func name dobj
130 @deffnx {C Function} scm_dynamic_func (name, dobj)
131 Return a ``handle'' for the func @var{name} in the shared object referred to
132 by @var{dobj}. The handle can be passed to @code{dynamic-call} to
133 actually call the function.
134
135 Regardless whether your C compiler prepends an underscore @samp{_} to the global
136 names in a program, you should @strong{not} include this underscore in
137 @var{name} since it will be added automatically when necessary.
138 @end deffn
139
140 Guile has static support for calling functions with no arguments,
141 @code{dynamic-call}.
142
143 @deffn {Scheme Procedure} dynamic-call func dobj
144 @deffnx {C Function} scm_dynamic_call (func, dobj)
145 Call the C function indicated by @var{func} and @var{dobj}.
146 The function is passed no arguments and its return value is
147 ignored. When @var{function} is something returned by
148 @code{dynamic-func}, call that function and ignore @var{dobj}.
149 When @var{func} is a string , look it up in @var{dynobj}; this
150 is equivalent to
151 @smallexample
152 (dynamic-call (dynamic-func @var{func} @var{dobj}) #f)
153 @end smallexample
154
155 Interrupts are deferred while the C function is executing (with
156 @code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}).
157 @end deffn
158
159 @code{dynamic-call} is not very powerful. It is mostly intended to be
160 used for calling specially written initialization functions that will
161 then add new primitives to Guile. For example, we do not expect that you
162 will dynamically link @file{libX11} with @code{dynamic-link} and then
163 construct a beautiful graphical user interface just by using
164 @code{dynamic-call}. Instead, the usual way would be to write a special
165 Guile-to-X11 glue library that has intimate knowledge about both Guile
166 and X11 and does whatever is necessary to make them inter-operate
167 smoothly. This glue library could then be dynamically linked into a
168 vanilla Guile interpreter and activated by calling its initialization
169 function. That function would add all the new types and primitives to
170 the Guile interpreter that it has to offer.
171
172 (There is actually another, better option: simply to create a
173 @file{libX11} wrapper in Scheme via the dynamic FFI. @xref{Dynamic FFI},
174 for more information.)
175
176 Given some set of C extensions to Guile, the next logical step is to
177 integrate these glue libraries into the module system of Guile so that
178 you can load new primitives into a running system just as you can load
179 new Scheme code.
180
181 @deffn {Scheme Procedure} load-extension lib init
182 @deffnx {C Function} scm_load_extension (lib, init)
183 Load and initialize the extension designated by LIB and INIT.
184 When there is no pre-registered function for LIB/INIT, this is
185 equivalent to
186
187 @lisp
188 (dynamic-call INIT (dynamic-link LIB))
189 @end lisp
190
191 When there is a pre-registered function, that function is called
192 instead.
193
194 Normally, there is no pre-registered function. This option exists
195 only for situations where dynamic linking is unavailable or unwanted.
196 In that case, you would statically link your program with the desired
197 library, and register its init function right after Guile has been
198 initialized.
199
200 LIB should be a string denoting a shared library without any file type
201 suffix such as ".so". The suffix is provided automatically. It
202 should also not contain any directory components. Libraries that
203 implement Guile Extensions should be put into the normal locations for
204 shared libraries. We recommend to use the naming convention
205 libguile-bla-blum for a extension related to a module `(bla blum)'.
206
207 The normal way for a extension to be used is to write a small Scheme
208 file that defines a module, and to load the extension into this
209 module. When the module is auto-loaded, the extension is loaded as
210 well. For example,
211
212 @lisp
213 (define-module (bla blum))
214
215 (load-extension "libguile-bla-blum" "bla_init_blum")
216 @end lisp
217 @end deffn
218
219 @node C Extensions
220 @subsection C Extensions
221
222 The most interesting application of dynamically linked libraries is
223 probably to use them for providing @emph{compiled code modules} to
224 Scheme programs. As much fun as programming in Scheme is, every now and
225 then comes the need to write some low-level C stuff to make Scheme even
226 more fun.
227
228 Not only can you put these new primitives into their own module (see the
229 previous section), you can even put them into a shared library that is
230 only then linked to your running Guile image when it is actually
231 needed.
232
233 An example will hopefully make everything clear. Suppose we want to
234 make the Bessel functions of the C library available to Scheme in the
235 module @samp{(math bessel)}. First we need to write the appropriate
236 glue code to convert the arguments and return values of the functions
237 from Scheme to C and back. Additionally, we need a function that will
238 add them to the set of Guile primitives. Because this is just an
239 example, we will only implement this for the @code{j0} function.
240
241 @smallexample
242 #include <math.h>
243 #include <libguile.h>
244
245 SCM
246 j0_wrapper (SCM x)
247 @{
248 return scm_from_double (j0 (scm_to_double (x, "j0")));
249 @}
250
251 void
252 init_math_bessel ()
253 @{
254 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
255 @}
256 @end smallexample
257
258 We can already try to bring this into action by manually calling the low
259 level functions for performing dynamic linking. The C source file needs
260 to be compiled into a shared library. Here is how to do it on
261 GNU/Linux, please refer to the @code{libtool} documentation for how to
262 create dynamically linkable libraries portably.
263
264 @smallexample
265 gcc -shared -o libbessel.so -fPIC bessel.c
266 @end smallexample
267
268 Now fire up Guile:
269
270 @lisp
271 (define bessel-lib (dynamic-link "./libbessel.so"))
272 (dynamic-call "init_math_bessel" bessel-lib)
273 (j0 2)
274 @result{} 0.223890779141236
275 @end lisp
276
277 The filename @file{./libbessel.so} should be pointing to the shared
278 library produced with the @code{gcc} command above, of course. The
279 second line of the Guile interaction will call the
280 @code{init_math_bessel} function which in turn will register the C
281 function @code{j0_wrapper} with the Guile interpreter under the name
282 @code{j0}. This function becomes immediately available and we can call
283 it from Scheme.
284
285 Fun, isn't it? But we are only half way there. This is what
286 @code{apropos} has to say about @code{j0}:
287
288 @smallexample
289 (apropos "j0")
290 @print{} (guile-user): j0 #<primitive-procedure j0>
291 @end smallexample
292
293 As you can see, @code{j0} is contained in the root module, where all
294 the other Guile primitives like @code{display}, etc live. In general,
295 a primitive is put into whatever module is the @dfn{current module} at
296 the time @code{scm_c_define_gsubr} is called.
297
298 A compiled module should have a specially named @dfn{module init
299 function}. Guile knows about this special name and will call that
300 function automatically after having linked in the shared library. For
301 our example, we replace @code{init_math_bessel} with the following code in
302 @file{bessel.c}:
303
304 @smallexample
305 void
306 init_math_bessel (void *unused)
307 @{
308 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
309 scm_c_export ("j0", NULL);
310 @}
311
312 void
313 scm_init_math_bessel_module ()
314 @{
315 scm_c_define_module ("math bessel", init_math_bessel, NULL);
316 @}
317 @end smallexample
318
319 The general pattern for the name of a module init function is:
320 @samp{scm_init_}, followed by the name of the module where the
321 individual hierarchical components are concatenated with underscores,
322 followed by @samp{_module}.
323
324 After @file{libbessel.so} has been rebuilt, we need to place the shared
325 library into the right place.
326
327 Once the module has been correctly installed, it should be possible to
328 use it like this:
329
330 @smallexample
331 guile> (load-extension "./libbessel.so" "scm_init_math_bessel_module")
332 guile> (use-modules (math bessel))
333 guile> (j0 2)
334 0.223890779141236
335 guile> (apropos "j0")
336 @print{} (math bessel): j0 #<primitive-procedure j0>
337 @end smallexample
338
339 That's it!
340
341
342 @node Modules and Extensions
343 @subsection Modules and Extensions
344
345 The new primitives that you add to Guile with @code{scm_c_define_gsubr}
346 (@pxref{Primitive Procedures}) or with any of the other mechanisms are
347 placed into the module that is current when the
348 @code{scm_c_define_gsubr} is executed. Extensions loaded from the REPL,
349 for example, will be placed into the @code{(guile-user)} module, if the
350 REPL module was not changed.
351
352 To define C primitives within a specific module, the simplest way is:
353
354 @example
355 (define-module (foo bar))
356 (load-extension "foobar-c-code" "foo_bar_init")
357 @end example
358
359 When loaded with @code{(use-modules (foo bar))}, the
360 @code{load-extension} call looks for the @file{foobar-c-code.so} (etc)
361 object file in the standard system locations, such as @file{/usr/lib}
362 or @file{/usr/local/lib}.
363
364 If someone installs your module to a non-standard location then the
365 object file won't be found. You can address this by inserting the
366 install location in the @file{foo/bar.scm} file. This is convenient
367 for the user and also guarantees the intended object is read, even if
368 stray older or newer versions are in the loader's path.
369
370 The usual way to specify an install location is with a @code{prefix}
371 at the configure stage, for instance @samp{./configure prefix=/opt}
372 results in library files as say @file{/opt/lib/foobar-c-code.so}.
373 When using Autoconf (@pxref{Top, , Introduction, autoconf, The GNU
374 Autoconf Manual}), the library location is in a @code{libdir}
375 variable. Its value is intended to be expanded by @command{make}, and
376 can by substituted into a source file like @file{foo.scm.in}
377
378 @example
379 (define-module (foo bar))
380 (load-extension "XXlibdirXX/foobar-c-code" "foo_bar_init")
381 @end example
382
383 @noindent
384 with the following in a @file{Makefile}, using @command{sed}
385 (@pxref{Top, , Introduction, sed, SED, A Stream Editor}),
386
387 @example
388 foo.scm: foo.scm.in
389 sed 's|XXlibdirXX|$(libdir)|' <foo.scm.in >foo.scm
390 @end example
391
392 The actual pattern @code{XXlibdirXX} is arbitrary, it's only something
393 which doesn't otherwise occur. If several modules need the value, it
394 can be easier to create one @file{foo/config.scm} with a define of the
395 @code{libdir} location, and use that as required.
396
397 @example
398 (define-module (foo config))
399 (define-public foo-config-libdir "XXlibdirXX"")
400 @end example
401
402 Such a file might have other locations too, for instance a data
403 directory for auxiliary files, or @code{localedir} if the module has
404 its own @code{gettext} message catalogue
405 (@pxref{Internationalization}).
406
407 When installing multiple C code objects, it can be convenient to put
408 them in a subdirectory of @code{libdir}, thus giving for example
409 @code{/usr/lib/foo/some-obj.so}. If the objects are only meant to be
410 used through the module, then a subdirectory keeps them out of sight.
411
412 It will be noted all of the above requires that the Scheme code to be
413 found in @code{%load-path} (@pxref{Build Config}). Presently it's
414 left up to the system administrator or each user to augment that path
415 when installing Guile modules in non-default locations. But having
416 reached the Scheme code, that code should take care of hitting any of
417 its own private files etc.
418
419 Presently there's no convention for having a Guile version number in
420 module C code filenames or directories. This is primarily because
421 there's no established principles for two versions of Guile to be
422 installed under the same prefix (eg. two both under @file{/usr}).
423 Assuming upward compatibility is maintained then this should be
424 unnecessary, and if compatibility is not maintained then it's highly
425 likely a package will need to be revisited anyway.
426
427 The present suggestion is that modules should assume when they're
428 installed under a particular @code{prefix} that there's a single
429 version of Guile there, and the @code{guile-config} at build time has
430 the necessary information about it. C code or Scheme code might adapt
431 itself accordingly (allowing for features not available in an older
432 version for instance).
433
434
435 @node Foreign Pointers
436 @subsection Foreign Pointers
437
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.
443
444 @menu
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.
449 @end menu
450
451 @node Foreign Types
452 @subsubsection Foreign Types
453
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}.
457
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
460 passed explicitly.
461
462 These ``C type values'' may be constructed using the constants and
463 procedures from the @code{(system foreign)} module, which may be loaded
464 like this:
465
466 @example
467 (use-modules (system foreign))
468 @end example
469
470 @code{(system foreign)} exports a number of values expressing the basic
471 C types:
472
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
484 signednesses.
485 @end defvr
486
487 In addition there are some convenience bindings for indicating types of
488 platform-dependent size:
489
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.
498 @end defvr
499
500 @defvr {Scheme Variable} void
501 The @code{void} type. It can be used as the first argument to
502 @code{make-foreign-function} to wrap a C function that returns nothing.
503 @end defvr
504
505 @node Foreign Variables
506 @subsubsection Foreign Variables
507
508 Given the types defined in the previous section, C pointers may be
509 looked up dynamically using @code{dynamic-pointer}.
510
511 @deffn {Scheme Procedure} dynamic-pointer name dobj
512 @deffnx {C Function} scm_dynamic_pointer (name, dobj)
513 Return a ``wrapped pointer'' for the symbol @var{name} in the shared
514 object referred to by @var{dobj}. The returned pointer points to a C
515 object.
516
517 This facility works by asking the dynamic linker for the address of a symbol,
518 then assuming that it aliases a value of a given type. Obviously, the user must
519 be very careful to ensure that the value actually is of the declared type, or
520 bad things will happen.
521
522 Regardless whether your C compiler prepends an underscore @samp{_} to the global
523 names in a program, you should @strong{not} include this underscore in
524 @var{name} since it will be added automatically when necessary.
525 @end deffn
526
527 For example, currently Guile has a variable, @code{scm_numptob}, as part
528 of its API. It is declared as a C @code{long}. So, to create a handle
529 pointing to that foreign value, we do:
530
531 @example
532 (use-modules (system foreign))
533 (define numptob (dynamic-pointer "scm_numptob" (dynamic-link)))
534 numptob
535 @result{} #<pointer 139984413364296>
536 @end example
537
538 A value returned by @code{dynamic-pointer} is a Scheme wrapper for a C
539 pointer.
540
541 @deffn {Scheme Procedure} pointer-address pointer
542 @deffnx {C Function} scm_pointer_address pointer
543 Return the numerical value of @var{pointer}.
544
545 @example
546 (pointer-address numptob)
547 @result{} 139984413364296 ; YMMV
548 @end example
549 @end deffn
550
551 @deffn {Scheme Procedure} make-pointer address [finalizer]
552 Return a foreign pointer object pointing to @var{address}. If
553 @var{finalizer} is passed, it should be a pointer to a one-argument C
554 function that will be called when the pointer object becomes
555 unreachable.
556 @end deffn
557
558 @defvr {Scheme Variable} %null-pointer
559 A foreign pointer whose value is 0.
560 @end defvr
561
562 @deffn {Scheme Procedure} null-pointer? pointer
563 Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
564 @end deffn
565
566
567 @node Void Pointers and Byte Access
568 @subsubsection Void Pointers and Byte Access
569
570 Wrapped pointers are untyped, so they are essentially equivalent to C
571 @code{void} pointers. As in C, the memory region pointed to by a
572 pointer can be accessed at the byte level. This is achieved using
573 @emph{bytevectors} (@pxref{Bytevectors}). The @code{(rnrs bytevector)}
574 module contains procedures that can be used to convert byte sequences to
575 Scheme objects such as strings, floating pointer numbers, or integers.
576
577 Pointers may be accessed as bytevectors.
578
579 @deffn {Scheme Procedure} pointer->bytevector pointer len [offset [uvec_type]]
580 @deffnx {C Function} scm_foreign_to_bytevector pointer len offset uvec_type
581 Return a bytevector aliasing the @var{len} bytes pointed to by
582 @var{pointer}.
583
584 The user may specify an alternate default interpretation for
585 the memory by passing the @var{uvec_type} argument, to indicate
586 that the memory is an array of elements of that type.
587 @var{uvec_type} should be something that
588 @code{uniform-vector-element-type} would return, like @code{f32}
589 or @code{s16}.
590
591 When @var{offset} is passed, it specifies the offset in bytes relative
592 to @var{pointer} of the memory region aliased by the returned
593 bytevector.
594
595 Mutating the returned bytevector mutates the memory pointed to by
596 @var{pointer}, so buckle your seatbelts.
597 @end deffn
598
599 @deffn {Scheme Procedure} bytevector->pointer bv [offset]
600 @deffnx {C Function} scm_bytevector_to_pointer bv offset
601 Return a pointer pointer aliasing the memory pointed to by @var{bv} or
602 @var{offset} bytes after @var{bv} when @var{offset} is passed.
603 @end deffn
604
605 In addition to these primitives, convenience procedures are available:
606
607 @deffn {Scheme Procedure} dereference-pointer pointer
608 Assuming @var{pointer} points to a memory region that holds a pointer,
609 return this pointer.
610 @end deffn
611
612 Going back to the @code{scm_numptob} example above, here is how we can
613 read its value as a C @code{long} integer:
614
615 @example
616 (use-modules (rnrs bytevectors))
617
618 (bytevector-uint-ref (pointer->bytevector numptob (sizeof long))
619 0 (native-endianness)
620 (sizeof long))
621 @result{} 8
622 @end example
623
624 If we wanted to corrupt Guile's internal state, we could set
625 @code{scm_numptob} to another value; but we shouldn't, because that
626 variable is not meant to be set. Indeed this point applies more widely:
627 the C API is a dangerous place to be. Not only might setting a value
628 crash your program, simply accessing the data pointed to by a dangling
629 pointer or similar can prove equally disastrous.
630
631 @node Foreign Structs
632 @subsubsection Foreign Structs
633
634 Finally, one last note on foreign values before moving on to actually
635 calling foreign functions. Sometimes you need to deal with C structs,
636 which requires interpreting each element of the struct according to the
637 its type, offset, and alignment. Guile has some primitives to support
638 this.
639
640 @deffn {Scheme Procedure} sizeof type
641 @deffnx {C Function} scm_sizeof type
642 Return the size of @var{type}, in bytes.
643
644 @var{type} should be a valid C type, like @code{int}.
645 Alternately @var{type} may be the symbol @code{*}, in which
646 case the size of a pointer is returned. @var{type} may
647 also be a list of types, in which case the size of a
648 @code{struct} with ABI-conventional packing is returned.
649 @end deffn
650
651 @deffn {Scheme Procedure} alignof type
652 @deffnx {C Function} scm_alignof type
653 Return the alignment of @var{type}, in bytes.
654
655 @var{type} should be a valid C type, like @code{int}.
656 Alternately @var{type} may be the symbol @code{*}, in which
657 case the alignment of a pointer is returned. @var{type} may
658 also be a list of types, in which case the alignment of a
659 @code{struct} with ABI-conventional packing is returned.
660 @end deffn
661
662 Guile also provides some convenience methods to pack and unpack foreign
663 pointers wrapping C structs.
664
665 @deffn {Scheme Procedure} make-c-struct types vals
666 Create a foreign pointer to a C struct containing @var{vals} with types
667 @code{types}.
668
669 @var{vals} and @code{types} should be lists of the same length.
670 @end deffn
671
672 @deffn {Scheme Procedure} parse-c-struct foreign types
673 Parse a foreign pointer to a C struct, returning a list of values.
674
675 @code{types} should be a list of C types.
676 @end deffn
677
678 For example, to create and parse the equivalent of a @code{struct @{
679 int64_t a; uint8_t b; @}}:
680
681 @example
682 (parse-c-struct (make-c-struct (list int64 uint8)
683 (list 300 43))
684 (list int64 uint8))
685 @result{} (300 43)
686 @end example
687
688 As yet, Guile only has convenience routines to support
689 conventionally-packed structs. But given the @code{bytevector->foreign}
690 and @code{foreign->bytevector} routines, one can create and parse
691 tightly packed structs and unions by hand. See the code for
692 @code{(system foreign)} for details.
693
694
695 @node Dynamic FFI
696 @subsection Dynamic FFI
697
698 Of course, the land of C is not all nouns and no verbs: there are
699 functions too, and Guile allows you to call them.
700
701 @deffn {Scheme Procedure} make-foreign-function return_type func_ptr arg_types
702 @deffnx {C Procedure} scm_make_foreign_function return_type func_ptr arg_types
703 Make a foreign function.
704
705 Given the foreign void pointer @var{func_ptr}, its argument and
706 return types @var{arg_types} and @var{return_type}, return a
707 procedure that will pass arguments to the foreign function
708 and return appropriate values.
709
710 @var{arg_types} should be a list of foreign types.
711 @code{return_type} should be a foreign type. @xref{Foreign Types}, for
712 more information on foreign types.
713 @end deffn
714
715 Here is a better definition of @code{(math bessel)}:
716
717 @example
718 (define-module (math bessel)
719 #:use-module (system foreign)
720 #:export (j0))
721
722 (define libm (dynamic-link "libm"))
723
724 (define j0
725 (make-foreign-function double
726 (dynamic-func "j0" libm)
727 (list double)))
728 @end example
729
730 That's it! No C at all.
731
732 Numeric arguments and return values from foreign functions are
733 represented as Scheme values. For example, @code{j0} in the above
734 example takes a Scheme number as its argument, and returns a Scheme
735 number.
736
737 Pointers may be passed to and returned from foreign functions as well.
738 In that case the type of the argument or return value should be the
739 symbol @code{*}, indicating a pointer. For example, the following
740 code makes @code{memcpy} available to Scheme:
741
742 @example
743 (define memcpy
744 (let ((this (dynamic-link)))
745 (make-foreign-function '*
746 (dynamic-func "memcpy" this)
747 (list '* '* size_t))))
748 @end example
749
750 To invoke @code{memcpy}, one must pass it foreign pointers:
751
752 @example
753 (use-modules (rnrs bytevectors))
754
755 (define src-bits
756 (u8-list->bytevector '(0 1 2 3 4 5 6 7)))
757 (define src
758 (bytevector->pointer src-bits))
759 (define dest
760 (bytevector->pointer (make-bytevector 16 0)))
761
762 (memcpy dest src (bytevector-length src-bits))
763
764 (bytevector->u8-list (pointer->bytevector dest 16))
765 @result{} (0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0)
766 @end example
767
768 One may also pass structs as values, passing structs as foreign
769 pointers. @xref{Foreign Structs}, for more information on how to express
770 struct types and struct values.
771
772 ``Out'' arguments are passed as foreign pointers. The memory pointed to
773 by the foreign pointer is mutated in place.
774
775 @example
776 ;; struct timeval @{
777 ;; time_t tv_sec; /* seconds */
778 ;; suseconds_t tv_usec; /* microseconds */
779 ;; @};
780 ;; assuming fields are of type "long"
781
782 (define gettimeofday
783 (let ((f (make-foreign-function
784 int
785 (dynamic-func "gettimeofday" (dynamic-link))
786 (list '* '*)))
787 (tv-type (list long long)))
788 (lambda ()
789 (let* ((timeval (make-c-struct tv-type (list 0 0)))
790 (ret (f timeval %null-pointer)))
791 (if (zero? ret)
792 (apply values (parse-c-struct timeval tv-type))
793 (error "gettimeofday returned an error" ret))))))
794
795 (gettimeofday)
796 @result{} 1270587589
797 @result{} 499553
798 @end example
799
800 As you can see, this interface to foreign functions is at a very low,
801 somewhat dangerous level. A contribution to Guile in the form of a
802 high-level FFI would be most welcome.
803
804 @c Local Variables:
805 @c TeX-master: "guile.texi"
806 @c End: