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