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