api-foreign.texi 37 KB

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