api-foreign.texi 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000-2004, 2007-2014, 2016-2017, 2021
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Foreign Function Interface
  7. @section Foreign Function Interface
  8. @cindex foreign function interface
  9. @cindex ffi
  10. Sometimes you need to use libraries written in C or Rust or some other
  11. non-Scheme language. More rarely, you might need to write some C to
  12. extend Guile. This section describes how to load these ``foreign
  13. libraries'', look up data and functions inside them, and so on.
  14. @menu
  15. * Foreign Libraries:: Dynamically linking to libraries.
  16. * Foreign Extensions:: Extending Guile in C with loadable modules.
  17. * Foreign Pointers:: Pointers to C data or functions.
  18. * Foreign Types:: Expressing C types in Scheme.
  19. * Foreign Functions:: Simple calls to C procedures.
  20. * Void Pointers and Byte Access:: Pointers into the ether.
  21. * Foreign Structs:: Packing and unpacking structs.
  22. * More Foreign Functions:: Advanced examples.
  23. @end menu
  24. @node Foreign Libraries
  25. @subsection Foreign Libraries
  26. Just as Guile can load up Scheme libraries at run-time, Guile can also
  27. load some system libraries written in C or other low-level languages.
  28. We refer to these as dynamically-loadable modules as @dfn{foreign
  29. libraries}, to distinguish them from native libraries written in Scheme
  30. or other languages implemented by Guile.
  31. @cindex foreign libraries
  32. @cindex libraries, foreign
  33. Foreign libraries usually come in two forms. Some foreign libraries are
  34. part of the operating system, such as the compression library
  35. @code{libz}. These shared libraries are built in such a way that many
  36. programs can use their functionality without duplicating their code.
  37. When a program written in C is built, it can declare that it uses a
  38. specific set of shared libraries.
  39. @cindex shared libraries
  40. @cindex libraries, shared
  41. When the program is run, the operating system takes care of locating and
  42. loading the shared libraries.
  43. The operating system components that can dynamically load and link
  44. shared libraries when a program is run are also available
  45. programmatically during a program's execution. This is the interface
  46. that's most useful for Guile, and this is what we mean in Guile when we
  47. refer to @dfn{dynamic linking}. Dynamic linking at run-time is
  48. sometimes called @dfn{dlopening}, to distinguish it from the dynamic
  49. linking that happens at program start-up.
  50. @cindex dynamic linking
  51. @cindex dlopening
  52. The other kind of foreign library is sometimes known as a module,
  53. plug-in, bundle, or an extension. These foreign libraries aren't meant
  54. to be linked to by C programs, but rather only to be dynamically loaded
  55. at run-time -- they extend some main program with functionality, but
  56. don't stand on their own. Sometimes a Guile library will implement some
  57. of its functionality in a loadable module.
  58. In either case, the interface on the Guile side is the same. You load
  59. the interface using @code{load-foreign-library}. The resulting foreign
  60. library object implements a simple lookup interface whereby the user can
  61. get addresses of data or code exported by the library. There is no
  62. facility to inspect foreign libraries; you have to know what's in there
  63. already before you look.
  64. Routines for loading foreign libraries and accessing their contents are
  65. implemented in the @code{(system foreign-library)} module.
  66. @example
  67. (use-modules (system foreign-library))
  68. @end example
  69. @deffn {Scheme Procedure} load-foreign-library [library] @
  70. [#:extensions=system-library-extensions] @
  71. [#:search-ltdl-library-path?=#t] @
  72. [#:search-path=search-path] @
  73. [#:search-system-paths?=#t] [#:lazy?=#t] [#:global=#f]
  74. [#:rename-on-cygwin?=#t]
  75. Find the shared library denoted by @var{library} (a string or @code{#f})
  76. and link it into the running Guile application. When everything works
  77. out, return a Scheme object suitable for representing the linked object
  78. file. Otherwise an error is thrown.
  79. If @var{library} argument is omitted, it defaults to @code{#f}. If
  80. @code{library} is false, the resulting foreign library gives access to
  81. all symbols available for dynamic linking in the main binary.
  82. It is not necessary to include any extension such as @code{.so} in
  83. @var{library}. For each system, Guile has a default set of extensions
  84. that it will try. On GNU systems, the default extension set is just
  85. @code{.so}; on Windows, just @code{.dll}; and on Darwin (Mac OS), it is
  86. @code{.bundle}, @code{.so}, and @code{.dylib}. Pass @code{#:extensions
  87. @var{extensions}} to override the default extensions list. If
  88. @var{library} contains one of the extensions, no extensions are tried,
  89. so it is possible to specify the extension if you know exactly what file
  90. to load.
  91. Unless @var{library} denotes an absolute file name or otherwise contains
  92. a directory separator (@code{/}, and also @code{\} on Windows), Guile
  93. will search for the library in the directories listed in
  94. @var{search-paths}. The default search path has three components, which
  95. can all be overriden by colon-delimited (semicolon on Windows)
  96. environment variables:
  97. @table @env
  98. @item GUILE_EXTENSIONS_PATH
  99. This is the main environment variable for users to add directories
  100. containing Guile extensions. The default value has no entries. This
  101. environment variable was added in Guile 3.0.6.
  102. @item LTDL_LIBRARY_PATH
  103. Before Guile 3.0.6, Guile loaded foreign libraries using @code{libltdl},
  104. the dynamic library loader provided by libtool. This loader used
  105. @env{LTDL_LIBRARY_PATH}, and for backwards compatibility we still
  106. support that path.
  107. However, @code{libltdl} would not only open @code{.so} (or @code{.dll}
  108. and so on) files, but also the @code{.la} files created by libtool. In
  109. installed libraries -- libraries that are in the target directories of
  110. @code{make install} -- @code{.la} files are never needed, to the extent
  111. that most GNU/Linux distributions remove them entirely. It is
  112. sufficient to just load the @code{.so} (or @code{.dll} and so on) files,
  113. which are always located in the same directory as the @code{.la} files.
  114. But for uninstalled dynamic libraries, like those in a build tree, the
  115. situation is a bit of a mess. If you have a project that uses libtool
  116. to build libraries -- which is the case for Guile, and for most projects
  117. using autotools -- and you build @file{foo.so} in directory @file{D},
  118. libtool will put @file{foo.la} in @file{D}, but @file{foo.so} gets put
  119. into @file{D/.libs}.
  120. Users were mostly oblivious to this situation, as @code{libltdl} had
  121. special logic to be able to read the @code{.la} file to know where to
  122. find the @code{.so}, even from an uninstalled build tree, preventing the
  123. existence of @file{.libs} from leaking out to the user.
  124. We don't use libltdl now, essentially for flexibility and
  125. error-reporting reasons. But, to keep this old use-case working, if
  126. @var{search-ltdl-library-path?} is true, we add each entry of
  127. @code{LTDL_LIBRARY_PATH} to the default extensions load path,
  128. additionally adding the @file{.libs} subdirextories for each entry, in
  129. case there are @file{.so} files there instead of alongside the
  130. @file{.la} files.
  131. @item GUILE_SYSTEM_EXTENSIONS_PATH
  132. The last path in Guile's search path belongs to Guile itself, and
  133. defaults to the libdir and the extensiondir, in that order. For
  134. example, if you install to @file{/opt/guile}, these would probably be
  135. @file{/opt/guile/lib} and
  136. @code{/opt/guile/lib/guile/@value{EFFECTIVE-VERSION}/extensions},
  137. respectively. @xref{Parallel Installations}, for more details on
  138. @code{extensionsdir}.
  139. @end table
  140. Finally, if no library is found in the search path, and if @var{library}
  141. is not absolute and does not include directory separators, and if
  142. @var{search-system-paths?} is true, the operating system may have its
  143. own logic for where to locate @var{library}. For example, on GNU, there
  144. will be a default set of paths (often @file{/usr/lib} and @file{/lib},
  145. though it depends on the system), and the @code{LD_LIBRARY_PATH}
  146. environment variable can add additional paths. Other operating systems
  147. have other conventions.
  148. Falling back to the operating system for search is usually not a great
  149. thing; it is a recipe for making programs that work on one machine but
  150. not on others. Still, when wrapping system libraries, it can be the
  151. only way to get things working at all.
  152. If @var{lazy?} is true (the default), Guile will request the operating
  153. system to resolve symbols used by the loaded library as they are first
  154. used. If @var{global?} is true, symbols defined by the loaded library
  155. will be available when other modules need to resolve symbols; the
  156. default is @code{#f}, which keeps symbols local.
  157. If @var{rename-on-cygwin?} is true (the default) -- on Cygwin hosts only
  158. -- the search behavior is modified such that a filename that starts with
  159. ``lib'' will be searched for under the name ``cyg'', as is customary for
  160. Cygwin.
  161. @end deffn
  162. The environment variables mentioned above are parsed when the
  163. foreign-library module is first loaded and bound to parameters. Null
  164. path components, for example the three components of
  165. @env{GUILE_SYSTEM_EXTENSIONS_PATH="::"}, are ignored.
  166. @deffn {Scheme Parameter} guile-extensions-path
  167. @deffnx {Scheme Parameter} ltdl-library-path
  168. @deffnx {Scheme Parameter} guile-system-extensions-path
  169. Parameters whose initial values are taken from
  170. @env{GUILE_EXTENSIONS_PATH}, @env{LTDL_LIBRARY_PATH}, and
  171. @env{GUILE_SYSTEM_EXTENSIONS_PATH}, respectively. @xref{Parameters}.
  172. The current values of these parameters are used when building the search
  173. path when @code{load-foreign-library} is called, unless the caller
  174. explicitly passes a @code{#:search-path} argument.
  175. @end deffn
  176. @deffn {Scheme Procedure} foreign-library? obj
  177. Return @code{#t} if @var{obj} is a foreign library, or @code{#f}
  178. otherwise.
  179. @end deffn
  180. @node Foreign Extensions
  181. @subsection Foreign Extensions
  182. One way to use shared libraries is to extend Guile. Such loadable
  183. modules generally define one distinguished initialization function that,
  184. when called, will use the @code{libguile} API to define procedures in
  185. the current module.
  186. Concretely, you might extend Guile with an implementation of the Bessel
  187. function, @code{j0}:
  188. @smallexample
  189. #include <math.h>
  190. #include <libguile.h>
  191. SCM
  192. j0_wrapper (SCM x)
  193. @{
  194. return scm_from_double (j0 (scm_to_double (x, "j0")));
  195. @}
  196. void
  197. init_math_bessel (void)
  198. @{
  199. scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
  200. @}
  201. @end smallexample
  202. The C source file would then need to be compiled into a shared library.
  203. On GNU/Linux, the compiler invocation might look like this:
  204. @smallexample
  205. gcc -shared -o bessel.so -fPIC bessel.c
  206. @end smallexample
  207. A good default place to put shared libraries that extend Guile is into
  208. the extensions dir. From the command line or a build script, invoke
  209. @code{pkg-config --variable=extensionsdir
  210. guile-@value{EFFECTIVE-VERSION}} to print the extensions dir.
  211. @xref{Parallel Installations}, for more details.
  212. Guile can load up @code{bessel.so} via @code{load-extension}.
  213. @deffn {Scheme Procedure} load-extension lib init
  214. @deffnx {C Function} scm_load_extension (lib, init)
  215. Load and initialize the extension designated by LIB and INIT.
  216. @end deffn
  217. The normal way for a extension to be used is to write a small Scheme
  218. file that defines a module, and to load the extension into this
  219. module. When the module is auto-loaded, the extension is loaded as
  220. well. For example:
  221. @lisp
  222. (define-module (math bessel)
  223. #:export (j0))
  224. (load-extension "bessel" "init_math_bessel")
  225. @end lisp
  226. This @code{load-extension} invocation loads the @code{bessel} library
  227. via @code{(load-foreign-library "bessel")}, then looks up the
  228. @code{init_math_bessel} symbol in the library, treating it as a function
  229. of no arguments, and calls that function.
  230. If you decide to put your extension outside the default search path for
  231. @code{load-foreign-library}, probably you should adapt the Scheme module
  232. to specify its absolute path. For example, if you use @code{automake}
  233. to build your extension and place it in @code{$(pkglibdir)}, you might
  234. define a build-parameters module that gets created by the build system:
  235. @example
  236. (define-module (math config)
  237. #:export (extensiondir))
  238. (define extensiondir "PKGLIBDIR")
  239. @end example
  240. This file would be @code{config.scm.in}. You would define a @code{make}
  241. rule to substitute in the absolute installed file name:
  242. @example
  243. config.scm: config.scm.in
  244. sed 's|PKGLIBDIR|$(pkglibdir)|' <$< >$@
  245. @end example
  246. Then your @code{(math bessel)} would import @code{(math config)}, then
  247. @code{(load-extension (in-vicinity extensiondir "bessel")
  248. "init_math_bessel")}.
  249. An alternate approach would be to rebind the
  250. @code{guile-extensions-path} parameter, or its corresponding environment
  251. variable, but note that changing those parameters applies to other users
  252. of @code{load-foreign-library} as well.
  253. Note that the new primitives that the extension adds to Guile with
  254. @code{scm_c_define_gsubr} (@pxref{Primitive Procedures}) or with any of
  255. the other mechanisms are placed into the module that is current when the
  256. @code{scm_c_define_gsubr} is executed, so to be clear about what goes
  257. vwhere it's best to include the @code{load-extension} in a module, as
  258. above. Alternately, the C code can use @code{scm_c_define_module} to
  259. specify which module is being created:
  260. @smallexample
  261. static void
  262. do_init (void *unused)
  263. @{
  264. scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
  265. scm_c_export ("j0", NULL);
  266. @}
  267. void
  268. init_math_bessel ()
  269. @{
  270. scm_c_define_module ("math bessel", do_init, NULL);
  271. @}
  272. @end smallexample
  273. And yet... if what we want is just the @code{j0} function, it seems like
  274. a lot of ceremony to have to compile a Guile-specific wrapper library
  275. complete with an initialization function and wraper module to allow
  276. Guile users to call it. There is another way, but to get there, we have
  277. to talk about function pointers and function types first. @xref{Foreign
  278. Functions}, to skip to the good parts.
  279. @node Foreign Pointers
  280. @subsection Foreign Pointers
  281. Foreign libraries are essentially key-value mappings, where the keys are
  282. names of definitions and the values are the addresses of those
  283. definitions. To look up the address of a definition, use
  284. @code{foreign-library-pointer} from the @code{(system foreign-library)}
  285. module.
  286. @deffn {Scheme Procedure} foreign-library-pointer lib name
  287. Return a ``wrapped pointer'' for the symbol @var{name} in the shared
  288. object referred to by @var{lib}. The returned pointer points to a C
  289. object.
  290. As a convenience, if @var{lib} is not a foreign library, it will be
  291. passed to @code{load-foreign-library}.
  292. @end deffn
  293. If we continue with the @code{bessel.so} example from before, we can get
  294. the address of the @code{init_math_bessel} function via:
  295. @example
  296. (use-modules (system foreign-library))
  297. (define init (foreign-library-pointer "bessel" "init_math_bessel"))
  298. init
  299. @result{} #<pointer 0x7fb35b1b4688>
  300. @end example
  301. A value returned by @code{foreign-library-pointer} is a Scheme wrapper
  302. for a C pointer. Pointers are a data type in Guile that is disjoint
  303. from all other types. The next section discusses ways to dereference
  304. pointers, but before then we describe the usual type predicates and so
  305. on.
  306. Note that the rest of the interfaces in this section are part of the
  307. @code{(system foreign)} library:
  308. @example
  309. (use-modules (system foreign))
  310. @end example
  311. @deffn {Scheme Procedure} pointer-address pointer
  312. @deffnx {C Function} scm_pointer_address (pointer)
  313. Return the numerical value of @var{pointer}.
  314. @example
  315. (pointer-address init)
  316. @result{} 139984413364296 ; YMMV
  317. @end example
  318. @end deffn
  319. @deffn {Scheme Procedure} make-pointer address [finalizer]
  320. Return a foreign pointer object pointing to @var{address}. If
  321. @var{finalizer} is passed, it should be a pointer to a one-argument C
  322. function that will be called when the pointer object becomes
  323. unreachable.
  324. @end deffn
  325. @deffn {Scheme Procedure} pointer? obj
  326. Return @code{#t} if @var{obj} is a pointer object, or @code{#f}
  327. otherwise.
  328. @end deffn
  329. @defvr {Scheme Variable} %null-pointer
  330. A foreign pointer whose value is 0.
  331. @end defvr
  332. @deffn {Scheme Procedure} null-pointer? pointer
  333. Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
  334. @end deffn
  335. For the purpose of passing SCM values directly to foreign functions, and
  336. allowing them to return SCM values, Guile also supports some unsafe
  337. casting operators.
  338. @deffn {Scheme Procedure} scm->pointer scm
  339. Return a foreign pointer object with the @code{object-address}
  340. of @var{scm}.
  341. @end deffn
  342. @deffn {Scheme Procedure} pointer->scm pointer
  343. Unsafely cast @var{pointer} to a Scheme object.
  344. Cross your fingers!
  345. @end deffn
  346. Sometimes you want to give C extensions access to the dynamic FFI. At
  347. that point, the names get confusing, because ``pointer'' can refer to a
  348. @code{SCM} object that wraps a pointer, or to a @code{void*} value. We
  349. will try to use ``pointer object'' to refer to Scheme objects, and
  350. ``pointer value'' to refer to @code{void *} values.
  351. @deftypefn {C Function} SCM scm_from_pointer (void *ptr, void (*finalizer) (void*))
  352. Create a pointer object from a pointer value.
  353. If @var{finalizer} is non-null, Guile arranges to call it on the pointer
  354. value at some point after the pointer object becomes collectable.
  355. @end deftypefn
  356. @deftypefn {C Function} void* scm_to_pointer (SCM obj)
  357. Unpack the pointer value from a pointer object.
  358. @end deftypefn
  359. @node Foreign Types
  360. @subsection Foreign Types
  361. From Scheme's perspective, foreign pointers are shards of chaos. The
  362. user can create a foreign pointer for any address, and do with it what
  363. they will. The only thing that lends a sense of order to the whole is a
  364. shared hallucination that certain storage locations have certain types.
  365. When making Scheme wrappers for foreign interfaces, we hide the madness
  366. by explicitly representing the the data types of parameters and fields.
  367. These ``foreign type values'' may be constructed using the constants and
  368. procedures from the @code{(system foreign)} module, which may be loaded
  369. like this:
  370. @example
  371. (use-modules (system foreign))
  372. @end example
  373. @code{(system foreign)} exports a number of values expressing the basic
  374. C types.
  375. @defvr {Scheme Variable} int8
  376. @defvrx {Scheme Variable} uint8
  377. @defvrx {Scheme Variable} uint16
  378. @defvrx {Scheme Variable} int16
  379. @defvrx {Scheme Variable} uint32
  380. @defvrx {Scheme Variable} int32
  381. @defvrx {Scheme Variable} uint64
  382. @defvrx {Scheme Variable} int64
  383. @defvrx {Scheme Variable} float
  384. @defvrx {Scheme Variable} double
  385. @defvrx {Scheme Variable} complex-double
  386. @defvrx {Scheme Variable} complex-float
  387. These values represent the C numeric types of the specified sizes and
  388. signednesses. @code{complex-float} and @code{complex-double} stand for
  389. C99 @code{float _Complex} and @code{double _Complex} respecively.
  390. @end defvr
  391. In addition there are some convenience bindings for indicating types of
  392. platform-dependent size.
  393. @defvr {Scheme Variable} int
  394. @defvrx {Scheme Variable} unsigned-int
  395. @defvrx {Scheme Variable} long
  396. @defvrx {Scheme Variable} unsigned-long
  397. @defvrx {Scheme Variable} short
  398. @defvrx {Scheme Variable} unsigned-short
  399. @defvrx {Scheme Variable} size_t
  400. @defvrx {Scheme Variable} ssize_t
  401. @defvrx {Scheme Variable} ptrdiff_t
  402. @defvrx {Scheme Variable} intptr_t
  403. @defvrx {Scheme Variable} uintptr_t
  404. Values exported by the @code{(system foreign)} module, representing C
  405. numeric types. For example, @code{long} may be @code{equal?} to
  406. @code{int64} on a 64-bit platform.
  407. @end defvr
  408. @defvr {Scheme Variable} void
  409. The @code{void} type. It can be used as the first argument to
  410. @code{pointer->procedure} to wrap a C function that returns nothing.
  411. @end defvr
  412. In addition, the symbol @code{*} is used by convention to denote pointer
  413. types. Procedures detailed in the following sections, such as
  414. @code{pointer->procedure}, accept it as a type descriptor.
  415. @node Foreign Functions
  416. @subsection Foreign Functions
  417. The most natural thing to do with a dynamic library is to grovel around
  418. in it for a function pointer: a @dfn{foreign function}. Load the
  419. @code{(system foreign)} module to use these Scheme interfaces.
  420. @example
  421. (use-modules (system foreign))
  422. @end example
  423. @deffn {Scheme Procedure} pointer->procedure return_type func_ptr arg_types @
  424. [#:return-errno?=#f]
  425. @deffnx {C Function} scm_pointer_to_procedure (return_type, func_ptr, arg_types)
  426. @deffnx {C Function} scm_pointer_to_procedure_with_errno (return_type, func_ptr, arg_types)
  427. Make a foreign function.
  428. Given the foreign void pointer @var{func_ptr}, its argument and
  429. return types @var{arg_types} and @var{return_type}, return a
  430. procedure that will pass arguments to the foreign function
  431. and return appropriate values.
  432. @var{arg_types} should be a list of foreign types.
  433. @code{return_type} should be a foreign type. @xref{Foreign Types}, for
  434. more information on foreign types.
  435. If @var{return-errno?} is true, or when calling
  436. @code{scm_pointer_to_procedure_with_errno}, the returned procedure will
  437. return two values, with @code{errno} as the second value.
  438. @end deffn
  439. Finally, in @code{(system foreign-library)} there is a convenient
  440. wrapper function, joining together @code{foreign-libary-pointer} and
  441. @code{procedure->pointer}:
  442. @deffn {Scheme Procedure} foreign-library-function lib name @
  443. [#:return-type=void] [#:arg-types='()] [#:return-errno?=#f]
  444. Load the address of @var{name} from @var{lib}, and treat it as a
  445. function taking arguments @var{arg-types} and returning
  446. @var{return-type}, optionally also with errno.
  447. An invocation of @code{foreign-library-function} is entirely equivalent
  448. to:
  449. @example
  450. (pointer->procedure @var{return-type}
  451. (foreign-library-pointer @var{lib} @var{name})
  452. @var{arg-types}
  453. #:return-errno? @var{return-errno?}).
  454. @end example
  455. @end deffn
  456. Pulling all this together, here is a better definition of @code{(math
  457. bessel)}:
  458. @example
  459. (define-module (math bessel)
  460. #:use-module (system foreign)
  461. #:use-module (system foreign-library)
  462. #:export (j0))
  463. (define j0
  464. (foreign-library-function "libm" "j0"
  465. #:return-type double
  466. #:arg-types (list double)))
  467. @end example
  468. That's it! No C at all.
  469. Before going on to more detailed examples, the next two sections discuss
  470. how to deal with data that is more complex than, say, @code{int8}.
  471. @xref{More Foreign Functions}, to continue with foreign function examples.
  472. @node Void Pointers and Byte Access
  473. @subsection Void Pointers and Byte Access
  474. Wrapped pointers are untyped, so they are essentially equivalent to C
  475. @code{void} pointers. As in C, the memory region pointed to by a
  476. pointer can be accessed at the byte level. This is achieved using
  477. @emph{bytevectors} (@pxref{Bytevectors}). The @code{(rnrs bytevectors)}
  478. module contains procedures that can be used to convert byte sequences to
  479. Scheme objects such as strings, floating point numbers, or integers.
  480. Load the @code{(system foreign)} module to use these Scheme interfaces.
  481. @example
  482. (use-modules (system foreign))
  483. @end example
  484. @deffn {Scheme Procedure} pointer->bytevector pointer len [offset [uvec_type]]
  485. @deffnx {C Function} scm_pointer_to_bytevector (pointer, len, offset, uvec_type)
  486. Return a bytevector aliasing the @var{len} bytes pointed to by
  487. @var{pointer}.
  488. The user may specify an alternate default interpretation for the memory
  489. by passing the @var{uvec_type} argument, to indicate that the memory is
  490. an array of elements of that type. @var{uvec_type} should be something
  491. that @code{array-type} would return, like @code{f32} or @code{s16}.
  492. When @var{offset} is passed, it specifies the offset in bytes relative
  493. to @var{pointer} of the memory region aliased by the returned
  494. bytevector.
  495. Mutating the returned bytevector mutates the memory pointed to by
  496. @var{pointer}, so buckle your seatbelts.
  497. @end deffn
  498. @deffn {Scheme Procedure} bytevector->pointer bv [offset]
  499. @deffnx {C Function} scm_bytevector_to_pointer (bv, offset)
  500. Return a pointer aliasing the memory pointed to by @var{bv} or
  501. @var{offset} bytes after @var{bv} when @var{offset} is passed.
  502. @end deffn
  503. In addition to these primitives, convenience procedures are available:
  504. @deffn {Scheme Procedure} dereference-pointer pointer
  505. Assuming @var{pointer} points to a memory region that holds a pointer,
  506. return this pointer.
  507. @end deffn
  508. @deffn {Scheme Procedure} string->pointer string [encoding]
  509. Return a foreign pointer to a nul-terminated copy of @var{string} in the
  510. given @var{encoding}, defaulting to the current locale encoding. The C
  511. string is freed when the returned foreign pointer becomes unreachable.
  512. This is the Scheme equivalent of @code{scm_to_stringn}.
  513. @end deffn
  514. @deffn {Scheme Procedure} pointer->string pointer [length] [encoding]
  515. Return the string representing the C string pointed to by @var{pointer}.
  516. If @var{length} is omitted or @code{-1}, the string is assumed to be
  517. nul-terminated. Otherwise @var{length} is the number of bytes in memory
  518. pointed to by @var{pointer}. The C string is assumed to be in the given
  519. @var{encoding}, defaulting to the current locale encoding.
  520. This is the Scheme equivalent of @code{scm_from_stringn}.
  521. @end deffn
  522. @cindex wrapped pointer types
  523. Most object-oriented C libraries use pointers to specific data
  524. structures to identify objects. It is useful in such cases to reify the
  525. different pointer types as disjoint Scheme types. The
  526. @code{define-wrapped-pointer-type} macro simplifies this.
  527. @deffn {Scheme Syntax} define-wrapped-pointer-type type-name pred wrap unwrap print
  528. Define helper procedures to wrap pointer objects into Scheme objects
  529. with a disjoint type. Specifically, this macro defines:
  530. @itemize
  531. @item @var{pred}, a predicate for the new Scheme type;
  532. @item @var{wrap}, a procedure that takes a pointer object and returns an
  533. object that satisfies @var{pred};
  534. @item @var{unwrap}, which does the reverse.
  535. @end itemize
  536. @var{wrap} preserves pointer identity, for two pointer objects @var{p1}
  537. and @var{p2} that are @code{equal?}, @code{(eq? (@var{wrap} @var{p1})
  538. (@var{wrap} @var{p2})) @result{} #t}.
  539. Finally, @var{print} should name a user-defined procedure to print such
  540. objects. The procedure is passed the wrapped object and a port to write
  541. to.
  542. For example, assume we are wrapping a C library that defines a type,
  543. @code{bottle_t}, and functions that can be passed @code{bottle_t *}
  544. pointers to manipulate them. We could write:
  545. @example
  546. (define-wrapped-pointer-type bottle
  547. bottle?
  548. wrap-bottle unwrap-bottle
  549. (lambda (b p)
  550. (format p "#<bottle of ~a ~x>"
  551. (bottle-contents b)
  552. (pointer-address (unwrap-bottle b)))))
  553. (define grab-bottle
  554. ;; Wrapper for `bottle_t *grab (void)'.
  555. (let ((grab (foreign-library-function libbottle "grab_bottle"
  556. #:return-type '*)))
  557. (lambda ()
  558. "Return a new bottle."
  559. (wrap-bottle (grab)))))
  560. (define bottle-contents
  561. ;; Wrapper for `const char *bottle_contents (bottle_t *)'.
  562. (let ((contents (foreign-library-function libbottle "bottle_contents"
  563. #:return-type '*
  564. #:arg-types '(*))))
  565. (lambda (b)
  566. "Return the contents of B."
  567. (pointer->string (contents (unwrap-bottle b))))))
  568. (write (grab-bottle))
  569. @result{} #<bottle of Ch@^ateau Haut-Brion 803d36>
  570. @end example
  571. In this example, @code{grab-bottle} is guaranteed to return a genuine
  572. @code{bottle} object satisfying @code{bottle?}. Likewise,
  573. @code{bottle-contents} errors out when its argument is not a genuine
  574. @code{bottle} object.
  575. @end deffn
  576. As another example, currently Guile has a variable, @code{scm_numptob},
  577. as part of its API. It is declared as a C @code{long}. So, to read its
  578. value, we can do:
  579. @example
  580. (use-modules (system foreign))
  581. (use-modules (rnrs bytevectors))
  582. (define numptob
  583. (foreign-library-pointer #f "scm_numptob"))
  584. numptob
  585. (bytevector-uint-ref (pointer->bytevector numptob (sizeof long))
  586. 0 (native-endianness)
  587. (sizeof long))
  588. @result{} 8
  589. @end example
  590. If we wanted to corrupt Guile's internal state, we could set
  591. @code{scm_numptob} to another value; but we shouldn't, because that
  592. variable is not meant to be set. Indeed this point applies more widely:
  593. the C API is a dangerous place to be. Not only might setting a value
  594. crash your program, simply accessing the data pointed to by a dangling
  595. pointer or similar can prove equally disastrous.
  596. @node Foreign Structs
  597. @subsection Foreign Structs
  598. Finally, one last note on foreign values before moving on to actually
  599. calling foreign functions. Sometimes you need to deal with C structs,
  600. which requires interpreting each element of the struct according to the
  601. its type, offset, and alignment. The @code{(system foreign)} module has
  602. some primitives to support this.
  603. @example
  604. (use-modules (system foreign))
  605. @end example
  606. @deffn {Scheme Procedure} sizeof type
  607. @deffnx {C Function} scm_sizeof (type)
  608. Return the size of @var{type}, in bytes.
  609. @var{type} should be a valid C type, like @code{int}.
  610. Alternately @var{type} may be the symbol @code{*}, in which
  611. case the size of a pointer is returned. @var{type} may
  612. also be a list of types, in which case the size of a
  613. @code{struct} with ABI-conventional packing is returned.
  614. @end deffn
  615. @deffn {Scheme Procedure} alignof type
  616. @deffnx {C Function} scm_alignof (type)
  617. Return the alignment of @var{type}, in bytes.
  618. @var{type} should be a valid C type, like @code{int}.
  619. Alternately @var{type} may be the symbol @code{*}, in which
  620. case the alignment of a pointer is returned. @var{type} may
  621. also be a list of types, in which case the alignment of a
  622. @code{struct} with ABI-conventional packing is returned.
  623. @end deffn
  624. Guile also provides some convenience methods to pack and unpack foreign
  625. pointers wrapping C structs.
  626. @deffn {Scheme Procedure} make-c-struct types vals
  627. Create a foreign pointer to a C struct containing @var{vals} with types
  628. @code{types}.
  629. @var{vals} and @code{types} should be lists of the same length.
  630. @end deffn
  631. @deffn {Scheme Procedure} parse-c-struct foreign types
  632. Parse a foreign pointer to a C struct, returning a list of values.
  633. @code{types} should be a list of C types.
  634. @end deffn
  635. For example, to create and parse the equivalent of a @code{struct @{
  636. int64_t a; uint8_t b; @}}:
  637. @example
  638. (parse-c-struct (make-c-struct (list int64 uint8)
  639. (list 300 43))
  640. (list int64 uint8))
  641. @result{} (300 43)
  642. @end example
  643. As yet, Guile only has convenience routines to support
  644. conventionally-packed structs. But given the @code{bytevector->pointer}
  645. and @code{pointer->bytevector} routines, one can create and parse
  646. tightly packed structs and unions by hand. See the code for
  647. @code{(system foreign)} for details.
  648. @node More Foreign Functions
  649. @subsection More Foreign Functions
  650. It is possible to pass pointers to foreign functions, and to return them
  651. as well. In that case the type of the argument or return value should
  652. be the symbol @code{*}, indicating a pointer. For example, the following
  653. code makes @code{memcpy} available to Scheme:
  654. @example
  655. (use-modules (system foreign))
  656. (define memcpy
  657. (foreign-library-function #f "memcpy"
  658. #:return-type '*
  659. #:arg-types (list '* '* size_t)))
  660. @end example
  661. To invoke @code{memcpy}, one must pass it foreign pointers:
  662. @example
  663. (use-modules (rnrs bytevectors))
  664. (define src-bits
  665. (u8-list->bytevector '(0 1 2 3 4 5 6 7)))
  666. (define src
  667. (bytevector->pointer src-bits))
  668. (define dest
  669. (bytevector->pointer (make-bytevector 16 0)))
  670. (memcpy dest src (bytevector-length src-bits))
  671. (bytevector->u8-list (pointer->bytevector dest 16))
  672. @result{} (0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0)
  673. @end example
  674. One may also pass structs as values, passing structs as foreign
  675. pointers. @xref{Foreign Structs}, for more information on how to express
  676. struct types and struct values.
  677. ``Out'' arguments are passed as foreign pointers. The memory pointed to
  678. by the foreign pointer is mutated in place.
  679. @example
  680. ;; struct timeval @{
  681. ;; time_t tv_sec; /* seconds */
  682. ;; suseconds_t tv_usec; /* microseconds */
  683. ;; @};
  684. ;; assuming fields are of type "long"
  685. (define gettimeofday
  686. (let ((f (foreign-library-function #f "gettimeofday"
  687. #:return-type int
  688. #:arg-types (list '* '*)))
  689. (tv-type (list long long)))
  690. (lambda ()
  691. (let* ((timeval (make-c-struct tv-type (list 0 0)))
  692. (ret (f timeval %null-pointer)))
  693. (if (zero? ret)
  694. (apply values (parse-c-struct timeval tv-type))
  695. (error "gettimeofday returned an error" ret))))))
  696. (gettimeofday)
  697. @result{} 1270587589
  698. @result{} 499553
  699. @end example
  700. As you can see, this interface to foreign functions is at a very low,
  701. somewhat dangerous level@footnote{A contribution to Guile in the form of
  702. a high-level FFI would be most welcome.}.
  703. @cindex callbacks
  704. The FFI can also work in the opposite direction: making Scheme
  705. procedures callable from C. This makes it possible to use Scheme
  706. procedures as ``callbacks'' expected by C function.
  707. @deffn {Scheme Procedure} procedure->pointer return-type proc arg-types
  708. @deffnx {C Function} scm_procedure_to_pointer (return_type, proc, arg_types)
  709. Return a pointer to a C function of type @var{return-type}
  710. taking arguments of types @var{arg-types} (a list) and
  711. behaving as a proxy to procedure @var{proc}. Thus
  712. @var{proc}'s arity, supported argument types, and return
  713. type should match @var{return-type} and @var{arg-types}.
  714. @end deffn
  715. As an example, here's how the C library's @code{qsort} array sorting
  716. function can be made accessible to Scheme (@pxref{Array Sort Function,
  717. @code{qsort},, libc, The GNU C Library Reference Manual}):
  718. @example
  719. (define qsort!
  720. (let ((qsort (foreign-library-function
  721. #f "qsort" #:arg-types (list '* size_t size_t '*))))
  722. (lambda (bv compare)
  723. ;; Sort bytevector BV in-place according to comparison
  724. ;; procedure COMPARE.
  725. (let ((ptr (procedure->pointer int
  726. (lambda (x y)
  727. ;; X and Y are pointers so,
  728. ;; for convenience, dereference
  729. ;; them before calling COMPARE.
  730. (compare (dereference-uint8* x)
  731. (dereference-uint8* y)))
  732. (list '* '*))))
  733. (qsort (bytevector->pointer bv)
  734. (bytevector-length bv) 1 ;; we're sorting bytes
  735. ptr)))))
  736. (define (dereference-uint8* ptr)
  737. ;; Helper function: dereference the byte pointed to by PTR.
  738. (let ((b (pointer->bytevector ptr 1)))
  739. (bytevector-u8-ref b 0)))
  740. (define bv
  741. ;; An unsorted array of bytes.
  742. (u8-list->bytevector '(7 1 127 3 5 4 77 2 9 0)))
  743. ;; Sort BV.
  744. (qsort! bv (lambda (x y) (- x y)))
  745. ;; Let's see what the sorted array looks like:
  746. (bytevector->u8-list bv)
  747. @result{} (0 1 2 3 4 5 7 9 77 127)
  748. @end example
  749. And voil@`a!
  750. Note that @code{procedure->pointer} is not supported (and not defined)
  751. on a few exotic architectures. Thus, user code may need to check
  752. @code{(defined? 'procedure->pointer)}. Nevertheless, it is available on
  753. many architectures, including (as of libffi 3.0.9) x86, ia64, SPARC,
  754. PowerPC, ARM, and MIPS, to name a few.
  755. @c Local Variables:
  756. @c TeX-master: "guile.texi"
  757. @c End: