api-foreign.texi 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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} size_t
  406. @defvrx {Scheme Variable} ssize_t
  407. @defvrx {Scheme Variable} ptrdiff_t
  408. Values exported by the @code{(system foreign)} module, representing C
  409. numeric types. For example, @code{long} may be @code{equal?} to
  410. @code{int64} on a 64-bit platform.
  411. @end defvr
  412. @defvr {Scheme Variable} void
  413. The @code{void} type. It can be used as the first argument to
  414. @code{pointer->procedure} to wrap a C function that returns nothing.
  415. @end defvr
  416. In addition, the symbol @code{*} is used by convention to denote pointer
  417. types. Procedures detailed in the following sections, such as
  418. @code{pointer->procedure}, accept it as a type descriptor.
  419. @node Foreign Variables
  420. @subsubsection Foreign Variables
  421. Pointers to variables in the current address space may be looked up
  422. dynamically using @code{dynamic-pointer}.
  423. @deffn {Scheme Procedure} dynamic-pointer name dobj
  424. @deffnx {C Function} scm_dynamic_pointer (name, dobj)
  425. Return a ``wrapped pointer'' for the symbol @var{name} in the shared
  426. object referred to by @var{dobj}. The returned pointer points to a C
  427. object.
  428. Regardless whether your C compiler prepends an underscore @samp{_} to the global
  429. names in a program, you should @strong{not} include this underscore in
  430. @var{name} since it will be added automatically when necessary.
  431. @end deffn
  432. For example, currently Guile has a variable, @code{scm_numptob}, as part
  433. of its API. It is declared as a C @code{long}. So, to create a handle
  434. pointing to that foreign value, we do:
  435. @example
  436. (use-modules (system foreign))
  437. (define numptob (dynamic-pointer "scm_numptob" (dynamic-link)))
  438. numptob
  439. @result{} #<pointer 0x7fb35b1b4688>
  440. @end example
  441. (The next section discusses ways to dereference pointers.)
  442. A value returned by @code{dynamic-pointer} is a Scheme wrapper for a C
  443. pointer.
  444. @deffn {Scheme Procedure} pointer-address pointer
  445. @deffnx {C Function} scm_pointer_address (pointer)
  446. Return the numerical value of @var{pointer}.
  447. @example
  448. (pointer-address numptob)
  449. @result{} 139984413364296 ; YMMV
  450. @end example
  451. @end deffn
  452. @deffn {Scheme Procedure} make-pointer address [finalizer]
  453. Return a foreign pointer object pointing to @var{address}. If
  454. @var{finalizer} is passed, it should be a pointer to a one-argument C
  455. function that will be called when the pointer object becomes
  456. unreachable.
  457. @end deffn
  458. @deffn {Scheme Procedure} pointer? obj
  459. Return @code{#t} if @var{obj} is a pointer object, @code{#f} otherwise.
  460. @end deffn
  461. @defvr {Scheme Variable} %null-pointer
  462. A foreign pointer whose value is 0.
  463. @end defvr
  464. @deffn {Scheme Procedure} null-pointer? pointer
  465. Return @code{#t} if @var{pointer} is the null pointer, @code{#f} otherwise.
  466. @end deffn
  467. For the purpose of passing SCM values directly to foreign functions, and
  468. allowing them to return SCM values, Guile also supports some unsafe
  469. casting operators.
  470. @deffn {Scheme Procedure} scm->pointer scm
  471. Return a foreign pointer object with the @code{object-address}
  472. of @var{scm}.
  473. @end deffn
  474. @deffn {Scheme Procedure} pointer->scm pointer
  475. Unsafely cast @var{pointer} to a Scheme object.
  476. Cross your fingers!
  477. @end deffn
  478. Sometimes you want to give C extensions access to the dynamic FFI. At
  479. that point, the names get confusing, because ``pointer'' can refer to a
  480. @code{SCM} object that wraps a pointer, or to a @code{void*} value. We
  481. will try to use ``pointer object'' to refer to Scheme objects, and
  482. ``pointer value'' to refer to @code{void *} values.
  483. @deftypefn {C Function} SCM scm_from_pointer (void *ptr, void (*finalizer) (void*))
  484. Create a pointer object from a pointer value.
  485. If @var{finalizer} is non-null, Guile arranges to call it on the pointer
  486. value at some point after the pointer object becomes collectable.
  487. @end deftypefn
  488. @deftypefn {C Function} void* scm_to_pointer (SCM obj)
  489. Unpack the pointer value from a pointer object.
  490. @end deftypefn
  491. @node Void Pointers and Byte Access
  492. @subsubsection Void Pointers and Byte Access
  493. Wrapped pointers are untyped, so they are essentially equivalent to C
  494. @code{void} pointers. As in C, the memory region pointed to by a
  495. pointer can be accessed at the byte level. This is achieved using
  496. @emph{bytevectors} (@pxref{Bytevectors}). The @code{(rnrs bytevectors)}
  497. module contains procedures that can be used to convert byte sequences to
  498. Scheme objects such as strings, floating point numbers, or integers.
  499. @deffn {Scheme Procedure} pointer->bytevector pointer len [offset [uvec_type]]
  500. @deffnx {C Function} scm_pointer_to_bytevector (pointer, len, offset, uvec_type)
  501. Return a bytevector aliasing the @var{len} bytes pointed to by
  502. @var{pointer}.
  503. The user may specify an alternate default interpretation for the memory
  504. by passing the @var{uvec_type} argument, to indicate that the memory is
  505. an array of elements of that type. @var{uvec_type} should be something
  506. that @code{array-type} would return, like @code{f32} or @code{s16}.
  507. When @var{offset} is passed, it specifies the offset in bytes relative
  508. to @var{pointer} of the memory region aliased by the returned
  509. bytevector.
  510. Mutating the returned bytevector mutates the memory pointed to by
  511. @var{pointer}, so buckle your seatbelts.
  512. @end deffn
  513. @deffn {Scheme Procedure} bytevector->pointer bv [offset]
  514. @deffnx {C Function} scm_bytevector_to_pointer (bv, offset)
  515. Return a pointer pointer aliasing the memory pointed to by @var{bv} or
  516. @var{offset} bytes after @var{bv} when @var{offset} is passed.
  517. @end deffn
  518. In addition to these primitives, convenience procedures are available:
  519. @deffn {Scheme Procedure} dereference-pointer pointer
  520. Assuming @var{pointer} points to a memory region that holds a pointer,
  521. return this pointer.
  522. @end deffn
  523. @deffn {Scheme Procedure} string->pointer string [encoding]
  524. Return a foreign pointer to a nul-terminated copy of @var{string} in the
  525. given @var{encoding}, defaulting to the current locale encoding. The C
  526. string is freed when the returned foreign pointer becomes unreachable.
  527. This is the Scheme equivalent of @code{scm_to_stringn}.
  528. @end deffn
  529. @deffn {Scheme Procedure} pointer->string pointer [length] [encoding]
  530. Return the string representing the C string pointed to by @var{pointer}.
  531. If @var{length} is omitted or @code{-1}, the string is assumed to be
  532. nul-terminated. Otherwise @var{length} is the number of bytes in memory
  533. pointed to by @var{pointer}. The C string is assumed to be in the given
  534. @var{encoding}, defaulting to the current locale encoding.
  535. This is the Scheme equivalent of @code{scm_from_stringn}.
  536. @end deffn
  537. @cindex wrapped pointer types
  538. Most object-oriented C libraries use pointers to specific data
  539. structures to identify objects. It is useful in such cases to reify the
  540. different pointer types as disjoint Scheme types. The
  541. @code{define-wrapped-pointer-type} macro simplifies this.
  542. @deffn {Scheme Syntax} define-wrapped-pointer-type type-name pred wrap unwrap print
  543. Define helper procedures to wrap pointer objects into Scheme objects
  544. with a disjoint type. Specifically, this macro defines:
  545. @itemize
  546. @item @var{pred}, a predicate for the new Scheme type;
  547. @item @var{wrap}, a procedure that takes a pointer object and returns an
  548. object that satisfies @var{pred};
  549. @item @var{unwrap}, which does the reverse.
  550. @end itemize
  551. @var{wrap} preserves pointer identity, for two pointer objects @var{p1}
  552. and @var{p2} that are @code{equal?}, @code{(eq? (@var{wrap} @var{p1})
  553. (@var{wrap} @var{p2})) @result{} #t}.
  554. Finally, @var{print} should name a user-defined procedure to print such
  555. objects. The procedure is passed the wrapped object and a port to write
  556. to.
  557. For example, assume we are wrapping a C library that defines a type,
  558. @code{bottle_t}, and functions that can be passed @code{bottle_t *}
  559. pointers to manipulate them. We could write:
  560. @example
  561. (define-wrapped-pointer-type bottle
  562. bottle?
  563. wrap-bottle unwrap-bottle
  564. (lambda (b p)
  565. (format p "#<bottle of ~a ~x>"
  566. (bottle-contents b)
  567. (pointer-address (unwrap-bottle b)))))
  568. (define grab-bottle
  569. ;; Wrapper for `bottle_t *grab (void)'.
  570. (let ((grab (pointer->procedure '*
  571. (dynamic-func "grab_bottle" libbottle)
  572. '())))
  573. (lambda ()
  574. "Return a new bottle."
  575. (wrap-bottle (grab)))))
  576. (define bottle-contents
  577. ;; Wrapper for `const char *bottle_contents (bottle_t *)'.
  578. (let ((contents (pointer->procedure '*
  579. (dynamic-func "bottle_contents"
  580. libbottle)
  581. '(*))))
  582. (lambda (b)
  583. "Return the contents of B."
  584. (pointer->string (contents (unwrap-bottle b))))))
  585. (write (grab-bottle))
  586. @result{} #<bottle of Ch@^ateau Haut-Brion 803d36>
  587. @end example
  588. In this example, @code{grab-bottle} is guaranteed to return a genuine
  589. @code{bottle} object satisfying @code{bottle?}. Likewise,
  590. @code{bottle-contents} errors out when its argument is not a genuine
  591. @code{bottle} object.
  592. @end deffn
  593. Going back to the @code{scm_numptob} example above, here is how we can
  594. read its value as a C @code{long} integer:
  595. @example
  596. (use-modules (rnrs bytevectors))
  597. (bytevector-uint-ref (pointer->bytevector numptob (sizeof long))
  598. 0 (native-endianness)
  599. (sizeof long))
  600. @result{} 8
  601. @end example
  602. If we wanted to corrupt Guile's internal state, we could set
  603. @code{scm_numptob} to another value; but we shouldn't, because that
  604. variable is not meant to be set. Indeed this point applies more widely:
  605. the C API is a dangerous place to be. Not only might setting a value
  606. crash your program, simply accessing the data pointed to by a dangling
  607. pointer or similar can prove equally disastrous.
  608. @node Foreign Structs
  609. @subsubsection Foreign Structs
  610. Finally, one last note on foreign values before moving on to actually
  611. calling foreign functions. Sometimes you need to deal with C structs,
  612. which requires interpreting each element of the struct according to the
  613. its type, offset, and alignment. Guile has some primitives to support
  614. this.
  615. @deffn {Scheme Procedure} sizeof type
  616. @deffnx {C Function} scm_sizeof (type)
  617. Return the size 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 size of a pointer is returned. @var{type} may
  621. also be a list of types, in which case the size of a
  622. @code{struct} with ABI-conventional packing is returned.
  623. @end deffn
  624. @deffn {Scheme Procedure} alignof type
  625. @deffnx {C Function} scm_alignof (type)
  626. Return the alignment of @var{type}, in bytes.
  627. @var{type} should be a valid C type, like @code{int}.
  628. Alternately @var{type} may be the symbol @code{*}, in which
  629. case the alignment of a pointer is returned. @var{type} may
  630. also be a list of types, in which case the alignment of a
  631. @code{struct} with ABI-conventional packing is returned.
  632. @end deffn
  633. Guile also provides some convenience methods to pack and unpack foreign
  634. pointers wrapping C structs.
  635. @deffn {Scheme Procedure} make-c-struct types vals
  636. Create a foreign pointer to a C struct containing @var{vals} with types
  637. @code{types}.
  638. @var{vals} and @code{types} should be lists of the same length.
  639. @end deffn
  640. @deffn {Scheme Procedure} parse-c-struct foreign types
  641. Parse a foreign pointer to a C struct, returning a list of values.
  642. @code{types} should be a list of C types.
  643. @end deffn
  644. For example, to create and parse the equivalent of a @code{struct @{
  645. int64_t a; uint8_t b; @}}:
  646. @example
  647. (parse-c-struct (make-c-struct (list int64 uint8)
  648. (list 300 43))
  649. (list int64 uint8))
  650. @result{} (300 43)
  651. @end example
  652. As yet, Guile only has convenience routines to support
  653. conventionally-packed structs. But given the @code{bytevector->pointer}
  654. and @code{pointer->bytevector} routines, one can create and parse
  655. tightly packed structs and unions by hand. See the code for
  656. @code{(system foreign)} for details.
  657. @node Dynamic FFI
  658. @subsection Dynamic FFI
  659. Of course, the land of C is not all nouns and no verbs: there are
  660. functions too, and Guile allows you to call them.
  661. @deffn {Scheme Procedure} pointer->procedure return_type func_ptr arg_types @
  662. [#:return-errno?=#f]
  663. @deffnx {C Function} scm_pointer_to_procedure (return_type, func_ptr, arg_types)
  664. @deffnx {C Function} scm_pointer_to_procedure_with_errno (return_type, func_ptr, arg_types)
  665. Make a foreign function.
  666. Given the foreign void pointer @var{func_ptr}, its argument and
  667. return types @var{arg_types} and @var{return_type}, return a
  668. procedure that will pass arguments to the foreign function
  669. and return appropriate values.
  670. @var{arg_types} should be a list of foreign types.
  671. @code{return_type} should be a foreign type. @xref{Foreign Types}, for
  672. more information on foreign types.
  673. If @var{return-errno?} is true, or when calling
  674. @code{scm_pointer_to_procedure_with_errno}, the returned procedure will
  675. return two values, with @code{errno} as the second value.
  676. @end deffn
  677. Here is a better definition of @code{(math bessel)}:
  678. @example
  679. (define-module (math bessel)
  680. #:use-module (system foreign)
  681. #:export (j0))
  682. (define libm (dynamic-link "libm"))
  683. (define j0
  684. (pointer->procedure double
  685. (dynamic-func "j0" libm)
  686. (list double)))
  687. @end example
  688. That's it! No C at all.
  689. Numeric arguments and return values from foreign functions are
  690. represented as Scheme values. For example, @code{j0} in the above
  691. example takes a Scheme number as its argument, and returns a Scheme
  692. number.
  693. Pointers may be passed to and returned from foreign functions as well.
  694. In that case the type of the argument or return value should be the
  695. symbol @code{*}, indicating a pointer. For example, the following
  696. code makes @code{memcpy} available to Scheme:
  697. @example
  698. (define memcpy
  699. (let ((this (dynamic-link)))
  700. (pointer->procedure '*
  701. (dynamic-func "memcpy" this)
  702. (list '* '* size_t))))
  703. @end example
  704. To invoke @code{memcpy}, one must pass it foreign pointers:
  705. @example
  706. (use-modules (rnrs bytevectors))
  707. (define src-bits
  708. (u8-list->bytevector '(0 1 2 3 4 5 6 7)))
  709. (define src
  710. (bytevector->pointer src-bits))
  711. (define dest
  712. (bytevector->pointer (make-bytevector 16 0)))
  713. (memcpy dest src (bytevector-length src-bits))
  714. (bytevector->u8-list (pointer->bytevector dest 16))
  715. @result{} (0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0)
  716. @end example
  717. One may also pass structs as values, passing structs as foreign
  718. pointers. @xref{Foreign Structs}, for more information on how to express
  719. struct types and struct values.
  720. ``Out'' arguments are passed as foreign pointers. The memory pointed to
  721. by the foreign pointer is mutated in place.
  722. @example
  723. ;; struct timeval @{
  724. ;; time_t tv_sec; /* seconds */
  725. ;; suseconds_t tv_usec; /* microseconds */
  726. ;; @};
  727. ;; assuming fields are of type "long"
  728. (define gettimeofday
  729. (let ((f (pointer->procedure
  730. int
  731. (dynamic-func "gettimeofday" (dynamic-link))
  732. (list '* '*)))
  733. (tv-type (list long long)))
  734. (lambda ()
  735. (let* ((timeval (make-c-struct tv-type (list 0 0)))
  736. (ret (f timeval %null-pointer)))
  737. (if (zero? ret)
  738. (apply values (parse-c-struct timeval tv-type))
  739. (error "gettimeofday returned an error" ret))))))
  740. (gettimeofday)
  741. @result{} 1270587589
  742. @result{} 499553
  743. @end example
  744. As you can see, this interface to foreign functions is at a very low,
  745. somewhat dangerous level@footnote{A contribution to Guile in the form of
  746. a high-level FFI would be most welcome.}.
  747. @cindex callbacks
  748. The FFI can also work in the opposite direction: making Scheme
  749. procedures callable from C. This makes it possible to use Scheme
  750. procedures as ``callbacks'' expected by C function.
  751. @deffn {Scheme Procedure} procedure->pointer return-type proc arg-types
  752. @deffnx {C Function} scm_procedure_to_pointer (return_type, proc, arg_types)
  753. Return a pointer to a C function of type @var{return-type}
  754. taking arguments of types @var{arg-types} (a list) and
  755. behaving as a proxy to procedure @var{proc}. Thus
  756. @var{proc}'s arity, supported argument types, and return
  757. type should match @var{return-type} and @var{arg-types}.
  758. @end deffn
  759. As an example, here's how the C library's @code{qsort} array sorting
  760. function can be made accessible to Scheme (@pxref{Array Sort Function,
  761. @code{qsort},, libc, The GNU C Library Reference Manual}):
  762. @example
  763. (define qsort!
  764. (let ((qsort (pointer->procedure void
  765. (dynamic-func "qsort"
  766. (dynamic-link))
  767. (list '* size_t size_t '*))))
  768. (lambda (bv compare)
  769. ;; Sort bytevector BV in-place according to comparison
  770. ;; procedure COMPARE.
  771. (let ((ptr (procedure->pointer int
  772. (lambda (x y)
  773. ;; X and Y are pointers so,
  774. ;; for convenience, dereference
  775. ;; them before calling COMPARE.
  776. (compare (dereference-uint8* x)
  777. (dereference-uint8* y)))
  778. (list '* '*))))
  779. (qsort (bytevector->pointer bv)
  780. (bytevector-length bv) 1 ;; we're sorting bytes
  781. ptr)))))
  782. (define (dereference-uint8* ptr)
  783. ;; Helper function: dereference the byte pointed to by PTR.
  784. (let ((b (pointer->bytevector ptr 1)))
  785. (bytevector-u8-ref b 0)))
  786. (define bv
  787. ;; An unsorted array of bytes.
  788. (u8-list->bytevector '(7 1 127 3 5 4 77 2 9 0)))
  789. ;; Sort BV.
  790. (qsort! bv (lambda (x y) (- x y)))
  791. ;; Let's see what the sorted array looks like:
  792. (bytevector->u8-list bv)
  793. @result{} (0 1 2 3 4 5 7 9 77 127)
  794. @end example
  795. And voil@`a!
  796. Note that @code{procedure->pointer} is not supported (and not defined)
  797. on a few exotic architectures. Thus, user code may need to check
  798. @code{(defined? 'procedure->pointer)}. Nevertheless, it is available on
  799. many architectures, including (as of libffi 3.0.9) x86, ia64, SPARC,
  800. PowerPC, ARM, and MIPS, to name a few.
  801. @c Local Variables:
  802. @c TeX-master: "guile.texi"
  803. @c End: