libffi.info 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. This is libffi.info, produced by makeinfo version 7.2 from libffi.texi.
  2. This manual is for libffi, a portable foreign function interface
  3. library.
  4. Copyright © 2008-2025 Anthony Green and Red Hat, Inc.
  5. Permission is hereby granted, free of charge, to any person obtaining
  6. a copy of this software and associated documentation files (the
  7. "Software"), to deal in the Software without restriction, including
  8. without limitation the rights to use, copy, modify, merge, publish,
  9. distribute, sublicense, and/or sell copies of the Software, and to
  10. permit persons to whom the Software is furnished to do so, subject to
  11. the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  17. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  18. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  19. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  20. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. INFO-DIR-SECTION Development
  22. START-INFO-DIR-ENTRY
  23. * libffi: (libffi). Portable foreign function interface library.
  24. END-INFO-DIR-ENTRY
  25. 
  26. File: libffi.info, Node: Top, Next: Introduction, Up: (dir)
  27. libffi
  28. ******
  29. This manual is for libffi, a portable foreign function interface
  30. library.
  31. Copyright © 2008-2025 Anthony Green and Red Hat, Inc.
  32. Permission is hereby granted, free of charge, to any person obtaining
  33. a copy of this software and associated documentation files (the
  34. "Software"), to deal in the Software without restriction, including
  35. without limitation the rights to use, copy, modify, merge, publish,
  36. distribute, sublicense, and/or sell copies of the Software, and to
  37. permit persons to whom the Software is furnished to do so, subject to
  38. the following conditions:
  39. The above copyright notice and this permission notice shall be
  40. included in all copies or substantial portions of the Software.
  41. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  42. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  43. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  44. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  45. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  46. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  47. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  48. * Menu:
  49. * Introduction:: What is libffi?
  50. * Using libffi:: How to use libffi.
  51. * Memory Usage:: Where memory for closures comes from.
  52. * Missing Features:: Things libffi can't do.
  53. * Index:: Index.
  54. 
  55. File: libffi.info, Node: Introduction, Next: Using libffi, Prev: Top, Up: Top
  56. 1 What is libffi?
  57. *****************
  58. Compilers for high level languages generate code that follow certain
  59. conventions. These conventions are necessary, in part, for separate
  60. compilation to work. One such convention is the “calling convention”.
  61. The calling convention is a set of assumptions made by the compiler
  62. about where function arguments will be found on entry to a function. A
  63. calling convention also specifies where the return value for a function
  64. is found. The calling convention is also sometimes called the “ABI” or
  65. “Application Binary Interface”.
  66. Some programs may not know at the time of compilation what arguments
  67. are to be passed to a function. For instance, an interpreter may be
  68. told at run-time about the number and types of arguments used to call a
  69. given function. ‘libffi’ can be used in such programs to provide a
  70. bridge from the interpreter program to compiled code.
  71. The ‘libffi’ library provides a portable, high level programming
  72. interface to various calling conventions. This allows a programmer to
  73. call any function specified by a call interface description at run time.
  74. FFI stands for Foreign Function Interface. A foreign function
  75. interface is the popular name for the interface that allows code written
  76. in one language to call code written in another language. The ‘libffi’
  77. library really only provides the lowest, machine dependent layer of a
  78. fully featured foreign function interface. A layer must exist above
  79. ‘libffi’ that handles type conversions for values passed between the two
  80. languages.
  81. 
  82. File: libffi.info, Node: Using libffi, Next: Memory Usage, Prev: Introduction, Up: Top
  83. 2 Using libffi
  84. **************
  85. * Menu:
  86. * The Basics:: The basic libffi API.
  87. * Simple Example:: A simple example.
  88. * Types:: libffi type descriptions.
  89. * Multiple ABIs:: Different passing styles on one platform.
  90. * The Closure API:: Writing a generic function.
  91. * Closure Example:: A closure example.
  92. * Thread Safety:: Thread safety.
  93. 
  94. File: libffi.info, Node: The Basics, Next: Simple Example, Up: Using libffi
  95. 2.1 The Basics
  96. ==============
  97. ‘libffi’ assumes that you have a pointer to the function you wish to
  98. call and that you know the number and types of arguments to pass it, as
  99. well as the return type of the function.
  100. The first thing you must do is create an ‘ffi_cif’ object that
  101. matches the signature of the function you wish to call. This is a
  102. separate step because it is common to make multiple calls using a single
  103. ‘ffi_cif’. The “cif” in ‘ffi_cif’ stands for Call InterFace. To
  104. prepare a call interface object, use the function ‘ffi_prep_cif’.
  105. -- Function: ffi_status ffi_prep_cif (ffi_cif *CIF, ffi_abi ABI,
  106. unsigned int NARGS, ffi_type *RTYPE, ffi_type **ARGTYPES)
  107. This initializes CIF according to the given parameters.
  108. ABI is the ABI to use; normally ‘FFI_DEFAULT_ABI’ is what you want.
  109. *note Multiple ABIs:: for more information.
  110. NARGS is the number of arguments that this function accepts.
  111. RTYPE is a pointer to an ‘ffi_type’ structure that describes the
  112. return type of the function. *Note Types::.
  113. ARGTYPES is a vector of ‘ffi_type’ pointers. ARGTYPES must have
  114. NARGS elements. If NARGS is 0, this argument is ignored.
  115. ‘ffi_prep_cif’ returns a ‘libffi’ status code, of type
  116. ‘ffi_status’. This will be either ‘FFI_OK’ if everything worked
  117. properly; ‘FFI_BAD_TYPEDEF’ if one of the ‘ffi_type’ objects is
  118. incorrect; or ‘FFI_BAD_ABI’ if the ABI parameter is invalid.
  119. If the function being called is variadic (varargs) then
  120. ‘ffi_prep_cif_var’ must be used instead of ‘ffi_prep_cif’.
  121. -- Function: ffi_status ffi_prep_cif_var (ffi_cif *CIF, ffi_abi ABI,
  122. unsigned int NFIXEDARGS, unsigned int NTOTALARGS, ffi_type
  123. *RTYPE, ffi_type **ARGTYPES)
  124. This initializes CIF according to the given parameters for a call
  125. to a variadic function. In general its operation is the same as
  126. for ‘ffi_prep_cif’ except that:
  127. NFIXEDARGS is the number of fixed arguments, prior to any variadic
  128. arguments. It must be greater than zero.
  129. NTOTALARGS the total number of arguments, including variadic and
  130. fixed arguments. ARGTYPES must have this many elements.
  131. ‘ffi_prep_cif_var’ will return ‘FFI_BAD_ARGTYPE’ if any of the
  132. variable argument types are ‘ffi_type_float’ (promote to
  133. ‘ffi_type_double’ first), or any integer type small than an int
  134. (promote to an int-sized type first).
  135. Note that, different cif's must be prepped for calls to the same
  136. function when different numbers of arguments are passed.
  137. Also note that a call to ‘ffi_prep_cif_var’ with
  138. NFIXEDARGS=NOTOTALARGS is NOT equivalent to a call to
  139. ‘ffi_prep_cif’.
  140. Note that the resulting ‘ffi_cif’ holds pointers to all the
  141. ‘ffi_type’ objects that were used during initialization. You must
  142. ensure that these type objects have a lifetime at least as long as that
  143. of the ‘ffi_cif’.
  144. To call a function using an initialized ‘ffi_cif’, use the ‘ffi_call’
  145. function:
  146. -- Function: void ffi_call (ffi_cif *CIF, void *FN, void *RVALUE, void
  147. **AVALUES)
  148. This calls the function FN according to the description given in
  149. CIF. CIF must have already been prepared using ‘ffi_prep_cif’.
  150. RVALUE is a pointer to a chunk of memory that will hold the result
  151. of the function call. This must be large enough to hold the
  152. result, no smaller than the system register size (generally 32 or
  153. 64 bits), and must be suitably aligned; it is the caller's
  154. responsibility to ensure this. If CIF declares that the function
  155. returns ‘void’ (using ‘ffi_type_void’), then RVALUE is ignored.
  156. In most situations, ‘libffi’ will handle promotion according to the
  157. ABI. However, for historical reasons, there is a special case with
  158. return values that must be handled by your code. In particular,
  159. for integral (not ‘struct’) types that are narrower than the system
  160. register size, the return value will be widened by ‘libffi’.
  161. ‘libffi’ provides a type, ‘ffi_arg’, that can be used as the return
  162. type. For example, if the CIF was defined with a return type of
  163. ‘char’, ‘libffi’ will try to store a full ‘ffi_arg’ into the return
  164. value.
  165. AVALUES is a vector of ‘void *’ pointers that point to the memory
  166. locations holding the argument values for a call. If CIF declares
  167. that the function has no arguments (i.e., NARGS was 0), then
  168. AVALUES is ignored.
  169. Note that while the return value must be register-sized, arguments
  170. should exactly match their declared type. For example, if an
  171. argument is a ‘short’, then the entry in AVALUES should point to an
  172. object declared as ‘short’; but if the return type is ‘short’, then
  173. RVALUE should point to an object declared as a larger type -
  174. usually ‘ffi_arg’.
  175. -- Function: const char * ffi_get_version (void)
  176. Returns the library version as a string. This string is also
  177. available at build time as the macro ‘FFI_VERSION_STRING’.
  178. -- Function: unsigned long ffi_get_version_number (void)
  179. Returns the library version as an unsigned long value where version
  180. "x.y.z" is represented as the number x*10000+y*100+z. This number
  181. is also available at build time as the macro ‘FFI_VERSION_NUMBER’.
  182. -- Function: unsigned int ffi_get_default_abi (void)
  183. Return the value of ‘FFI_DEFAULT_ABI’.
  184. -- Function: size_t ffi_get_closure_size (void)
  185. Return ‘sizeof(ffi_closure)’.
  186. 
  187. File: libffi.info, Node: Simple Example, Next: Types, Prev: The Basics, Up: Using libffi
  188. 2.2 Simple Example
  189. ==================
  190. Here is a trivial example that calls ‘puts’ a few times.
  191. #include <stdio.h>
  192. #include <ffi.h>
  193. int main()
  194. {
  195. ffi_cif cif;
  196. ffi_type *args[1];
  197. void *values[1];
  198. char *s;
  199. ffi_arg rc;
  200. /* Initialize the argument info vectors */
  201. args[0] = &ffi_type_pointer;
  202. values[0] = &s;
  203. /* Initialize the cif */
  204. if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
  205. &ffi_type_sint, args) == FFI_OK)
  206. {
  207. s = "Hello World!";
  208. ffi_call(&cif, (void(*)())puts, &rc, values);
  209. /* rc now holds the result of the call to puts */
  210. /* values holds a pointer to the function's arg, so to
  211. call puts() again all we need to do is change the
  212. value of s */
  213. s = "This is cool!";
  214. ffi_call(&cif, (void(*)())puts, &rc, values);
  215. }
  216. return 0;
  217. }
  218. 
  219. File: libffi.info, Node: Types, Next: Multiple ABIs, Prev: Simple Example, Up: Using libffi
  220. 2.3 Types
  221. =========
  222. * Menu:
  223. * Primitive Types:: Built-in types.
  224. * Structures:: Structure types.
  225. * Size and Alignment:: Size and alignment of types.
  226. * Arrays Unions Enums:: Arrays, unions, and enumerations.
  227. * Type Example:: Structure type example.
  228. * Complex:: Complex types.
  229. * Complex Type Example:: Complex type example.
  230. 
  231. File: libffi.info, Node: Primitive Types, Next: Structures, Up: Types
  232. 2.3.1 Primitive Types
  233. ---------------------
  234. ‘Libffi’ provides a number of built-in type descriptors that can be used
  235. to describe argument and return types:
  236. ‘ffi_type_void’
  237. The type ‘void’. This cannot be used for argument types, only for
  238. return values.
  239. ‘ffi_type_uint8’
  240. An unsigned, 8-bit integer type.
  241. ‘ffi_type_sint8’
  242. A signed, 8-bit integer type.
  243. ‘ffi_type_uint16’
  244. An unsigned, 16-bit integer type.
  245. ‘ffi_type_sint16’
  246. A signed, 16-bit integer type.
  247. ‘ffi_type_uint32’
  248. An unsigned, 32-bit integer type.
  249. ‘ffi_type_sint32’
  250. A signed, 32-bit integer type.
  251. ‘ffi_type_uint64’
  252. An unsigned, 64-bit integer type.
  253. ‘ffi_type_sint64’
  254. A signed, 64-bit integer type.
  255. ‘ffi_type_float’
  256. The C ‘float’ type.
  257. ‘ffi_type_double’
  258. The C ‘double’ type.
  259. ‘ffi_type_uchar’
  260. The C ‘unsigned char’ type.
  261. ‘ffi_type_schar’
  262. The C ‘signed char’ type. (Note that there is not an exact
  263. equivalent to the C ‘char’ type in ‘libffi’; ordinarily you should
  264. either use ‘ffi_type_schar’ or ‘ffi_type_uchar’ depending on
  265. whether ‘char’ is signed.)
  266. ‘ffi_type_ushort’
  267. The C ‘unsigned short’ type.
  268. ‘ffi_type_sshort’
  269. The C ‘short’ type.
  270. ‘ffi_type_uint’
  271. The C ‘unsigned int’ type.
  272. ‘ffi_type_sint’
  273. The C ‘int’ type.
  274. ‘ffi_type_ulong’
  275. The C ‘unsigned long’ type.
  276. ‘ffi_type_slong’
  277. The C ‘long’ type.
  278. ‘ffi_type_longdouble’
  279. On platforms that have a C ‘long double’ type, this is defined. On
  280. other platforms, it is not.
  281. ‘ffi_type_pointer’
  282. A generic ‘void *’ pointer. You should use this for all pointers,
  283. regardless of their real type.
  284. ‘ffi_type_complex_float’
  285. The C ‘_Complex float’ type.
  286. ‘ffi_type_complex_double’
  287. The C ‘_Complex double’ type.
  288. ‘ffi_type_complex_longdouble’
  289. The C ‘_Complex long double’ type. On platforms that have a C
  290. ‘long double’ type, this is defined. On other platforms, it is
  291. not.
  292. Each of these is of type ‘ffi_type’, so you must take the address
  293. when passing to ‘ffi_prep_cif’.
  294. 
  295. File: libffi.info, Node: Structures, Next: Size and Alignment, Prev: Primitive Types, Up: Types
  296. 2.3.2 Structures
  297. ----------------
  298. ‘libffi’ is perfectly happy passing structures back and forth. You must
  299. first describe the structure to ‘libffi’ by creating a new ‘ffi_type’
  300. object for it.
  301. -- Data type: ffi_type
  302. The ‘ffi_type’ has the following members:
  303. ‘size_t size’
  304. This is set by ‘libffi’; you should initialize it to zero.
  305. ‘unsigned short alignment’
  306. This is set by ‘libffi’; you should initialize it to zero.
  307. ‘unsigned short type’
  308. For a structure, this should be set to ‘FFI_TYPE_STRUCT’.
  309. ‘ffi_type **elements’
  310. This is a ‘NULL’-terminated array of pointers to ‘ffi_type’
  311. objects. There is one element per field of the struct.
  312. Note that ‘libffi’ has no special support for bit-fields. You
  313. must manage these manually.
  314. The ‘size’ and ‘alignment’ fields will be filled in by ‘ffi_prep_cif’
  315. or ‘ffi_prep_cif_var’, as needed.
  316. 
  317. File: libffi.info, Node: Size and Alignment, Next: Arrays Unions Enums, Prev: Structures, Up: Types
  318. 2.3.3 Size and Alignment
  319. ------------------------
  320. ‘libffi’ will set the ‘size’ and ‘alignment’ fields of an ‘ffi_type’
  321. object for you. It does so using its knowledge of the ABI.
  322. You might expect that you can simply read these fields for a type
  323. that has been laid out by ‘libffi’. However, there are some caveats.
  324. • The size or alignment of some of the built-in types may vary
  325. depending on the chosen ABI.
  326. • The size and alignment of a new structure type will not be set by
  327. ‘libffi’ until it has been passed to ‘ffi_prep_cif’ or
  328. ‘ffi_get_struct_offsets’.
  329. • A structure type cannot be shared across ABIs. Instead each ABI
  330. needs its own copy of the structure type.
  331. So, before examining these fields, it is safest to pass the
  332. ‘ffi_type’ object to ‘ffi_prep_cif’ or ‘ffi_get_struct_offsets’ first.
  333. This function will do all the needed setup.
  334. ffi_type *desired_type;
  335. ffi_abi desired_abi;
  336. ...
  337. ffi_cif cif;
  338. if (ffi_prep_cif (&cif, desired_abi, 0, desired_type, NULL) == FFI_OK)
  339. {
  340. size_t size = desired_type->size;
  341. unsigned short alignment = desired_type->alignment;
  342. }
  343. ‘libffi’ also provides a way to get the offsets of the members of a
  344. structure.
  345. -- Function: ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type
  346. *struct_type, size_t *offsets)
  347. Compute the offset of each element of the given structure type.
  348. ABI is the ABI to use; this is needed because in some cases the
  349. layout depends on the ABI.
  350. OFFSETS is an out parameter. The caller is responsible for
  351. providing enough space for all the results to be written - one
  352. element per element type in STRUCT_TYPE. If OFFSETS is ‘NULL’,
  353. then the type will be laid out but not otherwise modified. This
  354. can be useful for accessing the type's size or layout, as mentioned
  355. above.
  356. This function returns ‘FFI_OK’ on success; ‘FFI_BAD_ABI’ if ABI is
  357. invalid; or ‘FFI_BAD_TYPEDEF’ if STRUCT_TYPE is invalid in some
  358. way. Note that only ‘FFI_STRUCT’ types are valid here.
  359. 
  360. File: libffi.info, Node: Arrays Unions Enums, Next: Type Example, Prev: Size and Alignment, Up: Types
  361. 2.3.4 Arrays, Unions, and Enumerations
  362. --------------------------------------
  363. 2.3.4.1 Arrays
  364. ..............
  365. ‘libffi’ does not have direct support for arrays or unions. However,
  366. they can be emulated using structures.
  367. To emulate an array, simply create an ‘ffi_type’ using
  368. ‘FFI_TYPE_STRUCT’ with as many members as there are elements in the
  369. array.
  370. ffi_type array_type;
  371. ffi_type **elements
  372. int i;
  373. elements = malloc ((n + 1) * sizeof (ffi_type *));
  374. for (i = 0; i < n; ++i)
  375. elements[i] = array_element_type;
  376. elements[n] = NULL;
  377. array_type.size = array_type.alignment = 0;
  378. array_type.type = FFI_TYPE_STRUCT;
  379. array_type.elements = elements;
  380. Note that arrays cannot be passed or returned by value in C -
  381. structure types created like this should only be used to refer to
  382. members of real ‘FFI_TYPE_STRUCT’ objects.
  383. However, a phony array type like this will not cause any errors from
  384. ‘libffi’ if you use it as an argument or return type. This may be
  385. confusing.
  386. 2.3.4.2 Unions
  387. ..............
  388. A union can also be emulated using ‘FFI_TYPE_STRUCT’. In this case,
  389. however, you must make sure that the size and alignment match the real
  390. requirements of the union.
  391. One simple way to do this is to ensue that each element type is laid
  392. out. Then, give the new structure type a single element; the size of
  393. the largest element; and the largest alignment seen as well.
  394. This example uses the ‘ffi_prep_cif’ trick to ensure that each
  395. element type is laid out.
  396. ffi_abi desired_abi;
  397. ffi_type union_type;
  398. ffi_type **union_elements;
  399. int i;
  400. ffi_type element_types[2];
  401. element_types[1] = NULL;
  402. union_type.size = union_type.alignment = 0;
  403. union_type.type = FFI_TYPE_STRUCT;
  404. union_type.elements = element_types;
  405. for (i = 0; union_elements[i]; ++i)
  406. {
  407. ffi_cif cif;
  408. if (ffi_prep_cif (&cif, desired_abi, 0, union_elements[i], NULL) == FFI_OK)
  409. {
  410. if (union_elements[i]->size > union_type.size)
  411. {
  412. union_type.size = union_elements[i];
  413. size = union_elements[i]->size;
  414. }
  415. if (union_elements[i]->alignment > union_type.alignment)
  416. union_type.alignment = union_elements[i]->alignment;
  417. }
  418. }
  419. 2.3.4.3 Enumerations
  420. ....................
  421. ‘libffi’ does not have any special support for C ‘enum’s. Although any
  422. given ‘enum’ is implemented using a specific underlying integral type,
  423. exactly which type will be used cannot be determined by ‘libffi’ - it
  424. may depend on the values in the enumeration or on compiler flags such as
  425. ‘-fshort-enums’. *Note (gcc)Structures unions enumerations and
  426. bit-fields implementation::, for more information about how GCC handles
  427. enumerations.
  428. 
  429. File: libffi.info, Node: Type Example, Next: Complex, Prev: Arrays Unions Enums, Up: Types
  430. 2.3.5 Type Example
  431. ------------------
  432. The following example initializes a ‘ffi_type’ object representing the
  433. ‘tm’ struct from Linux's ‘time.h’.
  434. Here is how the struct is defined:
  435. struct tm {
  436. int tm_sec;
  437. int tm_min;
  438. int tm_hour;
  439. int tm_mday;
  440. int tm_mon;
  441. int tm_year;
  442. int tm_wday;
  443. int tm_yday;
  444. int tm_isdst;
  445. /* Those are for future use. */
  446. long int __tm_gmtoff__;
  447. __const char *__tm_zone__;
  448. };
  449. Here is the corresponding code to describe this struct to ‘libffi’:
  450. {
  451. ffi_type tm_type;
  452. ffi_type *tm_type_elements[12];
  453. int i;
  454. tm_type.size = tm_type.alignment = 0;
  455. tm_type.type = FFI_TYPE_STRUCT;
  456. tm_type.elements = tm_type_elements;
  457. for (i = 0; i < 9; i++)
  458. tm_type_elements[i] = &ffi_type_sint;
  459. tm_type_elements[9] = &ffi_type_slong;
  460. tm_type_elements[10] = &ffi_type_pointer;
  461. tm_type_elements[11] = NULL;
  462. /* tm_type can now be used to represent tm argument types and
  463. return types for ffi_prep_cif() */
  464. }
  465. 
  466. File: libffi.info, Node: Complex, Next: Complex Type Example, Prev: Type Example, Up: Types
  467. 2.3.6 Complex Types
  468. -------------------
  469. ‘libffi’ supports the complex types defined by the C99 standard
  470. (‘_Complex float’, ‘_Complex double’ and ‘_Complex long double’ with the
  471. built-in type descriptors ‘ffi_type_complex_float’,
  472. ‘ffi_type_complex_double’ and ‘ffi_type_complex_longdouble’.
  473. Custom complex types like ‘_Complex int’ can also be used. An
  474. ‘ffi_type’ object has to be defined to describe the complex type to
  475. ‘libffi’.
  476. -- Data type: ffi_type
  477. ‘size_t size’
  478. This must be manually set to the size of the complex type.
  479. ‘unsigned short alignment’
  480. This must be manually set to the alignment of the complex
  481. type.
  482. ‘unsigned short type’
  483. For a complex type, this must be set to ‘FFI_TYPE_COMPLEX’.
  484. ‘ffi_type **elements’
  485. This is a ‘NULL’-terminated array of pointers to ‘ffi_type’
  486. objects. The first element is set to the ‘ffi_type’ of the
  487. complex's base type. The second element must be set to
  488. ‘NULL’.
  489. The section *note Complex Type Example:: shows a way to determine the
  490. ‘size’ and ‘alignment’ members in a platform independent way.
  491. For platforms that have no complex support in ‘libffi’ yet, the
  492. functions ‘ffi_prep_cif’ and ‘ffi_prep_args’ abort the program if they
  493. encounter a complex type.
  494. 
  495. File: libffi.info, Node: Complex Type Example, Prev: Complex, Up: Types
  496. 2.3.7 Complex Type Example
  497. --------------------------
  498. This example demonstrates how to use complex types:
  499. #include <stdio.h>
  500. #include <ffi.h>
  501. #include <complex.h>
  502. void complex_fn(_Complex float cf,
  503. _Complex double cd,
  504. _Complex long double cld)
  505. {
  506. printf("cf=%f+%fi\ncd=%f+%fi\ncld=%f+%fi\n",
  507. (float)creal (cf), (float)cimag (cf),
  508. (float)creal (cd), (float)cimag (cd),
  509. (float)creal (cld), (float)cimag (cld));
  510. }
  511. int main()
  512. {
  513. ffi_cif cif;
  514. ffi_type *args[3];
  515. void *values[3];
  516. _Complex float cf;
  517. _Complex double cd;
  518. _Complex long double cld;
  519. /* Initialize the argument info vectors */
  520. args[0] = &ffi_type_complex_float;
  521. args[1] = &ffi_type_complex_double;
  522. args[2] = &ffi_type_complex_longdouble;
  523. values[0] = &cf;
  524. values[1] = &cd;
  525. values[2] = &cld;
  526. /* Initialize the cif */
  527. if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3,
  528. &ffi_type_void, args) == FFI_OK)
  529. {
  530. cf = 1.0 + 20.0 * I;
  531. cd = 300.0 + 4000.0 * I;
  532. cld = 50000.0 + 600000.0 * I;
  533. /* Call the function */
  534. ffi_call(&cif, (void (*)(void))complex_fn, 0, values);
  535. }
  536. return 0;
  537. }
  538. This is an example for defining a custom complex type descriptor for
  539. compilers that support them:
  540. /*
  541. * This macro can be used to define new complex type descriptors
  542. * in a platform independent way.
  543. *
  544. * name: Name of the new descriptor is ffi_type_complex_<name>.
  545. * type: The C base type of the complex type.
  546. */
  547. #define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \
  548. static ffi_type *ffi_elements_complex_##name [2] = { \
  549. (ffi_type *)(&ffitype), NULL \
  550. }; \
  551. struct struct_align_complex_##name { \
  552. char c; \
  553. _Complex type x; \
  554. }; \
  555. ffi_type ffi_type_complex_##name = { \
  556. sizeof(_Complex type), \
  557. offsetof(struct struct_align_complex_##name, x), \
  558. FFI_TYPE_COMPLEX, \
  559. (ffi_type **)ffi_elements_complex_##name \
  560. }
  561. /* Define new complex type descriptors using the macro: */
  562. /* ffi_type_complex_sint */
  563. FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint);
  564. /* ffi_type_complex_uchar */
  565. FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8);
  566. The new type descriptors can then be used like one of the built-in
  567. type descriptors in the previous example.
  568. 
  569. File: libffi.info, Node: Multiple ABIs, Next: The Closure API, Prev: Types, Up: Using libffi
  570. 2.4 Multiple ABIs
  571. =================
  572. A given platform may provide multiple different ABIs at once. For
  573. instance, the x86 platform has both ‘stdcall’ and ‘fastcall’ functions.
  574. ‘libffi’ provides some support for this. However, this is
  575. necessarily platform-specific.
  576. 
  577. File: libffi.info, Node: The Closure API, Next: Closure Example, Prev: Multiple ABIs, Up: Using libffi
  578. 2.5 The Closure API
  579. ===================
  580. ‘libffi’ also provides a way to write a generic function - a function
  581. that can accept and decode any combination of arguments. This can be
  582. useful when writing an interpreter, or to provide wrappers for arbitrary
  583. functions.
  584. This facility is called the “closure API”. Closures are not supported
  585. on all platforms; you can check the ‘FFI_CLOSURES’ define to determine
  586. whether they are supported on the current platform.
  587. Because closures work by assembling a tiny function at runtime, they
  588. require special allocation on platforms that have a non-executable heap.
  589. Memory management for closures is handled by a pair of functions:
  590. -- Function: void *ffi_closure_alloc (size_t SIZE, void **CODE)
  591. Allocate a chunk of memory holding SIZE bytes. This returns a
  592. pointer to the writable address, and sets *CODE to the
  593. corresponding executable address.
  594. SIZE should be sufficient to hold a ‘ffi_closure’ object.
  595. -- Function: void ffi_closure_free (void *WRITABLE)
  596. Free memory allocated using ‘ffi_closure_alloc’. The argument is
  597. the writable address that was returned.
  598. Once you have allocated the memory for a closure, you must construct
  599. a ‘ffi_cif’ describing the function call. Finally you can prepare the
  600. closure function:
  601. -- Function: ffi_status ffi_prep_closure_loc (ffi_closure *CLOSURE,
  602. ffi_cif *CIF, void (*FUN) (ffi_cif *CIF, void *RET, void
  603. **ARGS, void *USER_DATA), void *USER_DATA, void *CODELOC)
  604. Prepare a closure function. The arguments to
  605. ‘ffi_prep_closure_loc’ are:
  606. CLOSURE
  607. The address of a ‘ffi_closure’ object; this is the writable
  608. address returned by ‘ffi_closure_alloc’.
  609. CIF
  610. The ‘ffi_cif’ describing the function parameters. Note that
  611. this object, and the types to which it refers, must be kept
  612. alive until the closure itself is freed.
  613. USER_DATA
  614. An arbitrary datum that is passed, uninterpreted, to your
  615. closure function.
  616. CODELOC
  617. The executable address returned by ‘ffi_closure_alloc’.
  618. FUN
  619. The function which will be called when the closure is invoked.
  620. It is called with the arguments:
  621. CIF
  622. The ‘ffi_cif’ passed to ‘ffi_prep_closure_loc’.
  623. RET
  624. A pointer to the memory used for the function's return
  625. value.
  626. If the function is declared as returning ‘void’, then
  627. this value is garbage and should not be used.
  628. Otherwise, FUN must fill the object to which this points,
  629. following the same special promotion behavior as
  630. ‘ffi_call’. That is, in most cases, RET points to an
  631. object of exactly the size of the type specified when CIF
  632. was constructed. However, integral types narrower than
  633. the system register size are widened. In these cases
  634. your program may assume that RET points to an ‘ffi_arg’
  635. object.
  636. ARGS
  637. A vector of pointers to memory holding the arguments to
  638. the function.
  639. USER_DATA
  640. The same USER_DATA that was passed to
  641. ‘ffi_prep_closure_loc’.
  642. ‘ffi_prep_closure_loc’ will return ‘FFI_OK’ if everything went ok,
  643. and one of the other ‘ffi_status’ values on error.
  644. After calling ‘ffi_prep_closure_loc’, you can cast CODELOC to the
  645. appropriate pointer-to-function type.
  646. You may see old code referring to ‘ffi_prep_closure’. This function
  647. is deprecated, as it cannot handle the need for separate writable and
  648. executable addresses.
  649. 
  650. File: libffi.info, Node: Closure Example, Next: Thread Safety, Prev: The Closure API, Up: Using libffi
  651. 2.6 Closure Example
  652. ===================
  653. A trivial example that creates a new ‘puts’ by binding ‘fputs’ with
  654. ‘stdout’.
  655. #include <stdio.h>
  656. #include <ffi.h>
  657. /* Acts like puts with the file given at time of enclosure. */
  658. void puts_binding(ffi_cif *cif, void *ret, void* args[],
  659. void *stream)
  660. {
  661. *(ffi_arg *)ret = fputs(*(char **)args[0], (FILE *)stream);
  662. }
  663. typedef int (*puts_t)(char *);
  664. int main()
  665. {
  666. ffi_cif cif;
  667. ffi_type *args[1];
  668. ffi_closure *closure;
  669. void *bound_puts;
  670. int rc;
  671. /* Allocate closure and bound_puts */
  672. closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);
  673. if (closure)
  674. {
  675. /* Initialize the argument info vectors */
  676. args[0] = &ffi_type_pointer;
  677. /* Initialize the cif */
  678. if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
  679. &ffi_type_sint, args) == FFI_OK)
  680. {
  681. /* Initialize the closure, setting stream to stdout */
  682. if (ffi_prep_closure_loc(closure, &cif, puts_binding,
  683. stdout, bound_puts) == FFI_OK)
  684. {
  685. rc = ((puts_t)bound_puts)("Hello World!");
  686. /* rc now holds the result of the call to fputs */
  687. }
  688. }
  689. }
  690. /* Deallocate both closure, and bound_puts */
  691. ffi_closure_free(closure);
  692. return 0;
  693. }
  694. 
  695. File: libffi.info, Node: Thread Safety, Prev: Closure Example, Up: Using libffi
  696. 2.7 Thread Safety
  697. =================
  698. ‘libffi’ is not completely thread-safe. However, many parts are, and if
  699. you follow some simple rules, you can use it safely in a multi-threaded
  700. program.
  701. • ‘ffi_prep_cif’ may modify the ‘ffi_type’ objects passed to it. It
  702. is best to ensure that only a single thread prepares a given
  703. ‘ffi_cif’ at a time.
  704. • On some platforms, ‘ffi_prep_cif’ may modify the size and alignment
  705. of some types, depending on the chosen ABI. On these platforms, if
  706. you switch between ABIs, you must ensure that there is only one
  707. call to ‘ffi_prep_cif’ at a time.
  708. Currently the only affected platform is PowerPC and the only
  709. affected type is ‘long double’.
  710. 
  711. File: libffi.info, Node: Memory Usage, Next: Missing Features, Prev: Using libffi, Up: Top
  712. 3 Memory Usage
  713. **************
  714. Note that memory allocated by ‘ffi_closure_alloc’ and freed by
  715. ‘ffi_closure_free’ does not come from the same general pool of memory
  716. that ‘malloc’ and ‘free’ use. To accomodate security settings, ‘libffi’
  717. may aquire memory, for example, by mapping temporary files into multiple
  718. places in the address space (once to write out the closure, a second to
  719. execute it). The search follows this list, using the first that works:
  720. • A anonymous mapping (i.e. not file-backed)
  721. • ‘memfd_create()’, if the kernel supports it.
  722. • A file created in the directory referenced by the environment
  723. variable ‘LIBFFI_TMPDIR’.
  724. • Likewise for the environment variable ‘TMPDIR’.
  725. • A file created in ‘/tmp’.
  726. • A file created in ‘/var/tmp’.
  727. • A file created in ‘/dev/shm’.
  728. • A file created in the user's home directory (‘$HOME’).
  729. • A file created in any directory listed in ‘/etc/mtab’.
  730. • A file created in any directory listed in ‘/proc/mounts’.
  731. If security settings prohibit using any of these for closures,
  732. ‘ffi_closure_alloc’ will fail.
  733. 
  734. File: libffi.info, Node: Missing Features, Next: Index, Prev: Memory Usage, Up: Top
  735. 4 Missing Features
  736. ******************
  737. ‘libffi’ is missing a few features. We welcome patches to add support
  738. for these.
  739. • Variadic closures.
  740. • There is no support for bit fields in structures.
  741. • The "raw" API is undocumented.
  742. • The Go API is undocumented.
  743. 
  744. File: libffi.info, Node: Index, Prev: Missing Features, Up: Top
  745. Index
  746. *****
  747. �[index�]
  748. * Menu:
  749. * ABI: Introduction. (line 13)
  750. * Application Binary Interface: Introduction. (line 13)
  751. * calling convention: Introduction. (line 13)
  752. * cif: The Basics. (line 14)
  753. * closure API: The Closure API. (line 13)
  754. * closures: The Closure API. (line 13)
  755. * const char *: The Basics. (line 106)
  756. * FFI: Introduction. (line 31)
  757. * ffi_call: The Basics. (line 72)
  758. * ffi_closure_alloc: The Closure API. (line 19)
  759. * ffi_closure_free: The Closure API. (line 26)
  760. * FFI_CLOSURES: The Closure API. (line 13)
  761. * ffi_get_closure_size: The Basics. (line 118)
  762. * ffi_get_default_abi: The Basics. (line 115)
  763. * ffi_get_struct_offsets: Size and Alignment. (line 39)
  764. * ffi_get_version: The Basics. (line 106)
  765. * ffi_get_version_number: The Basics. (line 110)
  766. * ffi_prep_cif: The Basics. (line 16)
  767. * ffi_prep_cif_var: The Basics. (line 39)
  768. * ffi_prep_closure_loc: The Closure API. (line 34)
  769. * ffi_status: The Basics. (line 16)
  770. * ffi_status <1>: The Basics. (line 39)
  771. * ffi_status <2>: Size and Alignment. (line 39)
  772. * ffi_status <3>: The Closure API. (line 34)
  773. * ffi_type: Structures. (line 10)
  774. * ffi_type <1>: Structures. (line 10)
  775. * ffi_type <2>: Complex. (line 15)
  776. * ffi_type <3>: Complex. (line 15)
  777. * ffi_type_complex_double: Primitive Types. (line 82)
  778. * ffi_type_complex_float: Primitive Types. (line 79)
  779. * ffi_type_complex_longdouble: Primitive Types. (line 85)
  780. * ffi_type_double: Primitive Types. (line 41)
  781. * ffi_type_float: Primitive Types. (line 38)
  782. * ffi_type_longdouble: Primitive Types. (line 71)
  783. * ffi_type_pointer: Primitive Types. (line 75)
  784. * ffi_type_schar: Primitive Types. (line 47)
  785. * ffi_type_sint: Primitive Types. (line 62)
  786. * ffi_type_sint16: Primitive Types. (line 23)
  787. * ffi_type_sint32: Primitive Types. (line 29)
  788. * ffi_type_sint64: Primitive Types. (line 35)
  789. * ffi_type_sint8: Primitive Types. (line 17)
  790. * ffi_type_slong: Primitive Types. (line 68)
  791. * ffi_type_sshort: Primitive Types. (line 56)
  792. * ffi_type_uchar: Primitive Types. (line 44)
  793. * ffi_type_uint: Primitive Types. (line 59)
  794. * ffi_type_uint16: Primitive Types. (line 20)
  795. * ffi_type_uint32: Primitive Types. (line 26)
  796. * ffi_type_uint64: Primitive Types. (line 32)
  797. * ffi_type_uint8: Primitive Types. (line 14)
  798. * ffi_type_ulong: Primitive Types. (line 65)
  799. * ffi_type_ushort: Primitive Types. (line 53)
  800. * ffi_type_void: Primitive Types. (line 10)
  801. * Foreign Function Interface: Introduction. (line 31)
  802. * size_t: The Basics. (line 118)
  803. * unsigned int: The Basics. (line 115)
  804. * unsigned long: The Basics. (line 110)
  805. * void: The Basics. (line 72)
  806. * void <1>: The Closure API. (line 19)
  807. * void <2>: The Closure API. (line 26)
  808. 
  809. Tag Table:
  810. Node: Top1387
  811. Node: Introduction2909
  812. Node: Using libffi4569
  813. Node: The Basics5098
  814. Node: Simple Example10868
  815. Node: Types11925
  816. Node: Primitive Types12436
  817. Node: Structures14753
  818. Node: Size and Alignment15864
  819. Node: Arrays Unions Enums18135
  820. Node: Type Example21112
  821. Node: Complex22418
  822. Node: Complex Type Example23932
  823. Node: Multiple ABIs26984
  824. Node: The Closure API27367
  825. Node: Closure Example31281
  826. Node: Thread Safety32924
  827. Node: Memory Usage33757
  828. Node: Missing Features35032
  829. Node: Index35409
  830. 
  831. End Tag Table
  832. 
  833. Local Variables:
  834. coding: utf-8
  835. End: