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