remove "discouraged" infrastructure
[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 @cindex extensiondir
360 When loaded with @code{(use-modules (foo bar))}, the
361 @code{load-extension} call looks for the @file{foobar-c-code.so} (etc)
362 object file in Guile's @code{extensiondir}, which is usually a
363 subdirectory of the @code{libdir}. For example, if your libdir is
364 @file{/usr/lib}, the @code{extensiondir} for the Guile 2.0.@var{x}
365 series will be @file{/usr/lib/guile/2.0/}.
366
367 The extension path includes the major and minor version of Guile (the
368 ``effective version''), because Guile guarantees compatibility within a
369 given effective version. This allows you to install different versions
370 of the same extension for different versions of Guile.
371
372 If the extension is not found in the @code{extensiondir}, Guile will
373 also search the standard system locations, such as @file{/usr/lib} or
374 @file{/usr/local/lib}. It is preferable, however, to keep your extension
375 out of the system library path, to prevent unintended interference with
376 other dynamically-linked C libraries.
377
378 If someone installs your module to a non-standard location then the
379 object file won't be found. You can address this by inserting the
380 install location in the @file{foo/bar.scm} file. This is convenient
381 for the user and also guarantees the intended object is read, even if
382 stray older or newer versions are in the loader's path.
383
384 The usual way to specify an install location is with a @code{prefix}
385 at the configure stage, for instance @samp{./configure prefix=/opt}
386 results in library files as say @file{/opt/lib/foobar-c-code.so}.
387 When using Autoconf (@pxref{Top, , Introduction, autoconf, The GNU
388 Autoconf Manual}), the library location is in a @code{libdir}
389 variable. Its value is intended to be expanded by @command{make}, and
390 can by substituted into a source file like @file{foo.scm.in}
391
392 @example
393 (define-module (foo bar))
394 (load-extension "XXextensiondirXX/foobar-c-code" "foo_bar_init")
395 @end example
396
397 @noindent
398 with the following in a @file{Makefile}, using @command{sed}
399 (@pxref{Top, , Introduction, sed, SED, A Stream Editor}),
400
401 @example
402 foo.scm: foo.scm.in
403 sed 's|XXextensiondirXX|$(libdir)/guile/2.0|' <foo.scm.in >foo.scm
404 @end example
405
406 The actual pattern @code{XXextensiondirXX} is arbitrary, it's only something
407 which doesn't otherwise occur. If several modules need the value, it
408 can be easier to create one @file{foo/config.scm} with a define of the
409 @code{extensiondir} location, and use that as required.
410
411 @example
412 (define-module (foo config))
413 (define-public foo-config-extensiondir "XXextensiondirXX"")
414 @end example
415
416 Such a file might have other locations too, for instance a data
417 directory for auxiliary files, or @code{localedir} if the module has
418 its own @code{gettext} message catalogue
419 (@pxref{Internationalization}).
420
421 It will be noted all of the above requires that the Scheme code to be
422 found in @code{%load-path} (@pxref{Build Config}). Presently it's
423 left up to the system administrator or each user to augment that path
424 when installing Guile modules in non-default locations. But having
425 reached the Scheme code, that code should take care of hitting any of
426 its own private files etc.
427
428
429 @node Foreign Pointers
430 @subsection Foreign Pointers
431
432 The previous sections have shown how Guile can be extended at runtime by
433 loading compiled C extensions. This approach is all well and good, but
434 wouldn't it be nice if we didn't have to write any C at all? This
435 section takes up the problem of accessing C values from Scheme, and the
436 next discusses C functions.
437
438 @menu
439 * Foreign Types:: Expressing C types in Scheme.
440 * Foreign Variables:: Pointers to C symbols.
441 * Void Pointers and Byte Access:: Pointers into the ether.
442 * Foreign Structs:: Packing and unpacking structs.
443 @end menu
444
445 @node Foreign Types
446 @subsubsection Foreign Types
447
448 The first impedance mismatch that one sees between C and Scheme is that
449 in C, the storage locations (variables) are typed, but in Scheme types
450 are associated with values, not variables. @xref{Values and Variables}.
451
452 So when describing a C function or a C structure so that it can be
453 accessed from Scheme, the data types of the parameters or fields must be
454 passed explicitly.
455
456 These ``C type values'' may be constructed using the constants and
457 procedures from the @code{(system foreign)} module, which may be loaded
458 like this:
459
460 @example
461 (use-modules (system foreign))
462 @end example
463
464 @code{(system foreign)} exports a number of values expressing the basic
465 C types:
466
467 @defvr {Scheme Variable} int8
468 @defvrx {Scheme Variable} uint8
469 @defvrx {Scheme Variable} uint16
470 @defvrx {Scheme Variable} int16
471 @defvrx {Scheme Variable} uint32
472 @defvrx {Scheme Variable} int32
473 @defvrx {Scheme Variable} uint64
474 @defvrx {Scheme Variable} int64
475 @defvrx {Scheme Variable} float
476 @defvrx {Scheme Variable} double
477 These values represent the C numeric types of the specified sizes and
478 signednesses.
479 @end defvr
480
481 In addition there are some convenience bindings for indicating types of
482 platform-dependent size:
483
484 @defvr {Scheme Variable} int
485 @defvrx {Scheme Variable} unsigned-int
486 @defvrx {Scheme Variable} long
487 @defvrx {Scheme Variable} unsigned-long
488 @defvrx {Scheme Variable} size_t
489 Values exported by the @code{(system foreign)} module, representing C
490 numeric types. For example, @code{long} may be @code{equal?} to
491 @code{int64} on a 64-bit platform.
492 @end defvr
493
494 @defvr {Scheme Variable} void
495 The @code{void} type. It can be used as the first argument to
496 @code{make-foreign-function} to wrap a C function that returns nothing.
497 @end defvr
498
499 @node Foreign Variables
500 @subsubsection Foreign Variables
501
502 Pointers to variables in the current address space may be looked up
503 dynamically using @code{dynamic-pointer}.
504
505 @deffn {Scheme Procedure} dynamic-pointer name dobj
506 @deffnx {C Function} scm_dynamic_pointer (name, dobj)
507 Return a ``wrapped pointer'' for the symbol @var{name} in the shared
508 object referred to by @var{dobj}. The returned pointer points to a C
509 object.
510
511 Regardless whether your C compiler prepends an underscore @samp{_} to the global
512 names in a program, you should @strong{not} include this underscore in
513 @var{name} since it will be added automatically when necessary.
514 @end deffn
515
516 For example, currently Guile has a variable, @code{scm_numptob}, as part
517 of its API. It is declared as a C @code{long}. So, to create a handle
518 pointing to that foreign value, we do:
519
520 @example
521 (use-modules (system foreign))
522 (define numptob (dynamic-pointer "scm_numptob" (dynamic-link)))
523 numptob
524 @result{} #<pointer 0x7fb35b1b4688>
525 @end example
526
527 (The next section discusses ways to dereference pointers.)
528
529 A value returned by @code{dynamic-pointer} is a Scheme wrapper for a C
530 pointer.
531
532 @deffn {Scheme Procedure} pointer-address pointer
533 @deffnx {C Function} scm_pointer_address pointer
534 Return the numerical value of @var{pointer}.
535
536 @example
537 (pointer-address numptob)
538 @result{} 139984413364296 ; YMMV
539 @end example
540 @end deffn
541
542 @deffn {Scheme Procedure} make-pointer address [finalizer]
543 Return a foreign pointer object pointing to @var{address}. If
544 @var{finalizer} is passed, it should be a pointer to a one-argument C
545 function that will be called when the pointer object becomes
546 unreachable.
547 @end deffn
548
549 @defvr {Scheme Variable} %null-pointer
550 A foreign pointer whose value is 0.
551 @end defvr
552
553 @deffn {Scheme Procedure} null-pointer? pointer
554 Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
555 @end deffn
556
557
558 @node Void Pointers and Byte Access
559 @subsubsection Void Pointers and Byte Access
560
561 Wrapped pointers are untyped, so they are essentially equivalent to C
562 @code{void} pointers. As in C, the memory region pointed to by a
563 pointer can be accessed at the byte level. This is achieved using
564 @emph{bytevectors} (@pxref{Bytevectors}). The @code{(rnrs bytevector)}
565 module contains procedures that can be used to convert byte sequences to
566 Scheme objects such as strings, floating point numbers, or integers.
567
568 @deffn {Scheme Procedure} pointer->bytevector pointer len [offset [uvec_type]]
569 @deffnx {C Function} scm_foreign_to_bytevector pointer len offset uvec_type
570 Return a bytevector aliasing the @var{len} bytes pointed to by
571 @var{pointer}.
572
573 The user may specify an alternate default interpretation for
574 the memory by passing the @var{uvec_type} argument, to indicate
575 that the memory is an array of elements of that type.
576 @var{uvec_type} should be something that
577 @code{uniform-vector-element-type} would return, like @code{f32}
578 or @code{s16}.
579
580 When @var{offset} is passed, it specifies the offset in bytes relative
581 to @var{pointer} of the memory region aliased by the returned
582 bytevector.
583
584 Mutating the returned bytevector mutates the memory pointed to by
585 @var{pointer}, so buckle your seatbelts.
586 @end deffn
587
588 @deffn {Scheme Procedure} bytevector->pointer bv [offset]
589 @deffnx {C Function} scm_bytevector_to_pointer bv offset
590 Return a pointer pointer aliasing the memory pointed to by @var{bv} or
591 @var{offset} bytes after @var{bv} when @var{offset} is passed.
592 @end deffn
593
594 In addition to these primitives, convenience procedures are available:
595
596 @deffn {Scheme Procedure} dereference-pointer pointer
597 Assuming @var{pointer} points to a memory region that holds a pointer,
598 return this pointer.
599 @end deffn
600
601 Going back to the @code{scm_numptob} example above, here is how we can
602 read its value as a C @code{long} integer:
603
604 @example
605 (use-modules (rnrs bytevectors))
606
607 (bytevector-uint-ref (pointer->bytevector numptob (sizeof long))
608 0 (native-endianness)
609 (sizeof long))
610 @result{} 8
611 @end example
612
613 If we wanted to corrupt Guile's internal state, we could set
614 @code{scm_numptob} to another value; but we shouldn't, because that
615 variable is not meant to be set. Indeed this point applies more widely:
616 the C API is a dangerous place to be. Not only might setting a value
617 crash your program, simply accessing the data pointed to by a dangling
618 pointer or similar can prove equally disastrous.
619
620 @node Foreign Structs
621 @subsubsection Foreign Structs
622
623 Finally, one last note on foreign values before moving on to actually
624 calling foreign functions. Sometimes you need to deal with C structs,
625 which requires interpreting each element of the struct according to the
626 its type, offset, and alignment. Guile has some primitives to support
627 this.
628
629 @deffn {Scheme Procedure} sizeof type
630 @deffnx {C Function} scm_sizeof type
631 Return the size of @var{type}, in bytes.
632
633 @var{type} should be a valid C type, like @code{int}.
634 Alternately @var{type} may be the symbol @code{*}, in which
635 case the size of a pointer is returned. @var{type} may
636 also be a list of types, in which case the size of a
637 @code{struct} with ABI-conventional packing is returned.
638 @end deffn
639
640 @deffn {Scheme Procedure} alignof type
641 @deffnx {C Function} scm_alignof type
642 Return the alignment 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 alignment of a pointer is returned. @var{type} may
647 also be a list of types, in which case the alignment of a
648 @code{struct} with ABI-conventional packing is returned.
649 @end deffn
650
651 Guile also provides some convenience methods to pack and unpack foreign
652 pointers wrapping C structs.
653
654 @deffn {Scheme Procedure} make-c-struct types vals
655 Create a foreign pointer to a C struct containing @var{vals} with types
656 @code{types}.
657
658 @var{vals} and @code{types} should be lists of the same length.
659 @end deffn
660
661 @deffn {Scheme Procedure} parse-c-struct foreign types
662 Parse a foreign pointer to a C struct, returning a list of values.
663
664 @code{types} should be a list of C types.
665 @end deffn
666
667 For example, to create and parse the equivalent of a @code{struct @{
668 int64_t a; uint8_t b; @}}:
669
670 @example
671 (parse-c-struct (make-c-struct (list int64 uint8)
672 (list 300 43))
673 (list int64 uint8))
674 @result{} (300 43)
675 @end example
676
677 As yet, Guile only has convenience routines to support
678 conventionally-packed structs. But given the @code{bytevector->foreign}
679 and @code{foreign->bytevector} routines, one can create and parse
680 tightly packed structs and unions by hand. See the code for
681 @code{(system foreign)} for details.
682
683
684 @node Dynamic FFI
685 @subsection Dynamic FFI
686
687 Of course, the land of C is not all nouns and no verbs: there are
688 functions too, and Guile allows you to call them.
689
690 @deffn {Scheme Procedure} make-foreign-function return_type func_ptr arg_types
691 @deffnx {C Procedure} scm_make_foreign_function return_type func_ptr arg_types
692 Make a foreign function.
693
694 Given the foreign void pointer @var{func_ptr}, its argument and
695 return types @var{arg_types} and @var{return_type}, return a
696 procedure that will pass arguments to the foreign function
697 and return appropriate values.
698
699 @var{arg_types} should be a list of foreign types.
700 @code{return_type} should be a foreign type. @xref{Foreign Types}, for
701 more information on foreign types.
702 @end deffn
703
704 Here is a better definition of @code{(math bessel)}:
705
706 @example
707 (define-module (math bessel)
708 #:use-module (system foreign)
709 #:export (j0))
710
711 (define libm (dynamic-link "libm"))
712
713 (define j0
714 (make-foreign-function double
715 (dynamic-func "j0" libm)
716 (list double)))
717 @end example
718
719 That's it! No C at all.
720
721 Numeric arguments and return values from foreign functions are
722 represented as Scheme values. For example, @code{j0} in the above
723 example takes a Scheme number as its argument, and returns a Scheme
724 number.
725
726 Pointers may be passed to and returned from foreign functions as well.
727 In that case the type of the argument or return value should be the
728 symbol @code{*}, indicating a pointer. For example, the following
729 code makes @code{memcpy} available to Scheme:
730
731 @example
732 (define memcpy
733 (let ((this (dynamic-link)))
734 (make-foreign-function '*
735 (dynamic-func "memcpy" this)
736 (list '* '* size_t))))
737 @end example
738
739 To invoke @code{memcpy}, one must pass it foreign pointers:
740
741 @example
742 (use-modules (rnrs bytevectors))
743
744 (define src-bits
745 (u8-list->bytevector '(0 1 2 3 4 5 6 7)))
746 (define src
747 (bytevector->pointer src-bits))
748 (define dest
749 (bytevector->pointer (make-bytevector 16 0)))
750
751 (memcpy dest src (bytevector-length src-bits))
752
753 (bytevector->u8-list (pointer->bytevector dest 16))
754 @result{} (0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0)
755 @end example
756
757 One may also pass structs as values, passing structs as foreign
758 pointers. @xref{Foreign Structs}, for more information on how to express
759 struct types and struct values.
760
761 ``Out'' arguments are passed as foreign pointers. The memory pointed to
762 by the foreign pointer is mutated in place.
763
764 @example
765 ;; struct timeval @{
766 ;; time_t tv_sec; /* seconds */
767 ;; suseconds_t tv_usec; /* microseconds */
768 ;; @};
769 ;; assuming fields are of type "long"
770
771 (define gettimeofday
772 (let ((f (make-foreign-function
773 int
774 (dynamic-func "gettimeofday" (dynamic-link))
775 (list '* '*)))
776 (tv-type (list long long)))
777 (lambda ()
778 (let* ((timeval (make-c-struct tv-type (list 0 0)))
779 (ret (f timeval %null-pointer)))
780 (if (zero? ret)
781 (apply values (parse-c-struct timeval tv-type))
782 (error "gettimeofday returned an error" ret))))))
783
784 (gettimeofday)
785 @result{} 1270587589
786 @result{} 499553
787 @end example
788
789 As you can see, this interface to foreign functions is at a very low,
790 somewhat dangerous level. A contribution to Guile in the form of a
791 high-level FFI would be most welcome.
792
793 @c Local Variables:
794 @c TeX-master: "guile.texi"
795 @c End: