Inhaltsverzeichnis

This manual is for Libffi, a portable foreign-function interface library.

   Copyright (C) 2008, 2010, 2011 Red Hat, Inc.

   Permission is granted to copy, distribute and/or modify this
   document under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2, or
   (at your option) any later version.  A copy of the license is
   included in the section entitled "GNU General Public License".

File: libffi.info, Node: Top, Next: Introduction, Up: (dir)

libffi

This manual is for Libffi, a portable foreign-function interface library.

   Copyright (C) 2008, 2010, 2011 Red Hat, Inc.

   Permission is granted to copy, distribute and/or modify this
   document under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2, or
   (at your option) any later version.  A copy of the license is
   included in the section entitled "GNU General Public License".

File: libffi.info, Node: Introduction, Next: Using libffi, Prev: Top, Up: Top

What is libffi?

Compilers for high level languages generate code that follow certain conventions. These conventions are necessary, in part, for separate compilation to work. One such convention is the „calling convention“. The calling convention is a set of assumptions made by the compiler about where function arguments will be found on entry to a function. A calling convention also specifies where the return value for a function is found. The calling convention is also sometimes called the „ABI“ or „Application Binary Interface“.

Some programs may not know at the time of compilation what arguments are to be passed to a function. For instance, an interpreter may be told at run-time about the number and types of arguments used to call a given function. `Libffi' can be used in such programs to provide a bridge from the interpreter program to compiled code.

The `libffi' library provides a portable, high level programming interface to various calling conventions. This allows a programmer to call any function specified by a call interface description at run time.

FFI stands for Foreign Function Interface. A foreign function interface is the popular name for the interface that allows code written in one language to call code written in another language. The `libffi' library really only provides the lowest, machine dependent layer of a fully featured foreign function interface. A layer must exist above `libffi' that handles type conversions for values passed between the two languages. 

Using libffi

File: libffi.info, Node: The Basics, Next: Simple Example, Up: Using libffi

2.1 The Basics

`Libffi' assumes that you have a pointer to the function you wish to call and that you know the number and types of arguments to pass it, as well as the return type of the function.

 The first thing you must do is create an `ffi_cif' object that

matches the signature of the function you wish to call. This is a separate step because it is common to make multiple calls using a single `ffi_cif'. The „cif“ in `ffi_cif' stands for Call InterFace. To prepare a call interface object, use the function `ffi_prep_cif'.

Function: ffi_status ffi_prep_cif (ffi_cif *CIF, ffi_abi ABI, unsigned int NARGS, ffi_type *RTYPE, ffi_type **ARGTYPES)

This initializes CIF according to the given parameters.

`ffi_prep_cif' returns a `libffi' status code, of type `ffi_status'. This will be either `FFI_OK' if everything worked properly; `FFI_BAD_TYPEDEF' if one of the `ffi_type' objects is incorrect; or `FFI_BAD_ABI' if the ABI parameter is invalid.

If the function being called is variadic (varargs) then `ffi_prep_cif_var' must be used instead of `ffi_prep_cif'.

Function: ffi_status ffi_prep_cif_var (ffi_cif *CIF, ffi_abi varabi, unsigned int NFIXEDARGS, unsigned int varntotalargs, ffi_type *RTYPE, ffi_type **ARGTYPES)

This initializes CIF according to the given parameters for a call to a variadic function. In general it's operation is the same as for `ffi_prep_cif' except that:

Note that, different cif's must be prepped for calls to the same function when different numbers of arguments are passed.

Also note that a call to `ffi_prep_cif_var' with NFIXEDARGS=NOTOTALARGS is NOT equivalent to a call to `ffi_prep_cif'.

To call a function using an initialized `ffi_cif', use the ffi_call' function:

Function: void ffi_call (ffi_cif *CIF, void *FN, void *RVALUE, void **AVALUES)

This calls the function FN according to the description given in CIF. CIF must have already been prepared using `ffi_prep_cif'.

Simple Example

Here is a trivial example that calls `puts' a few times.

     #include <stdio.h>
     #include <ffi.h>
 
     int main()
     {
       ffi_cif cif;
       ffi_type *args[1];
       void *values[1];
       char *s;
       int rc;
 
       /* Initialize the argument info vectors */
       args[0] = &ffi_type_pointer;
       values[0] = &s;
 
       /* Initialize the cif */
       if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
     		       &ffi_type_uint, args) == FFI_OK)
         {
           s = "Hello World!";
           ffi_call(&cif, puts, &rc, values);
           /* rc now holds the result of the call to puts */
 
           /* values holds a pointer to the function's arg, so to
              call puts() again all we need to do is change the
              value of s */
           s = "This is cool!";
           ffi_call(&cif, puts, &rc, values);
         }
 
       return 0;
     }

Types

Primitive Types

`Libffi' provides a number of built-in type descriptors that can be used to describe argument and return types:

Each of these is of type `ffi_type', so you must take the address when passing to `ffi_prep_cif'.

Structures

Although `libffi' has no special support for unions or bit-fields, it is perfectly happy passing structures back and forth. You must first describe the structure to `libffi' by creating a new `ffi_type' object for it.

ffi_type:

The `ffi_type' has the following members:

* `size_t size' \\ This is set by `libffi'; you should initialize it to zero.
* `unsigned short alignment' \\ This is set by `libffi'; you should initialize it to zero.
* `unsigned short type' \\ For a structure, this should be set to `FFI_TYPE_STRUCT'.
* `ffi_type **elements' \\ This is a `NULL'-terminated array of pointers to `ffi_type' objects. There is one element per field of the struct.

Type Example

The following example initializes a `ffi_type' object representing the `tm' struct from Linux's `time.h'.

Here is how the struct is defined:

     struct tm {
         int tm_sec;
         int tm_min;
         int tm_hour;
         int tm_mday;
         int tm_mon;
         int tm_year;
         int tm_wday;
         int tm_yday;
         int tm_isdst;
         /* Those are for future use. */
         long int __tm_gmtoff__;
         __const char *__tm_zone__;
     };

Here is the corresponding code to describe this struct to `libffi':

         {
           ffi_type tm_type;
           ffi_type *tm_type_elements[12];
           int i;
 
           tm_type.size = tm_type.alignment = 0;
           tm_type.elements = &tm_type_elements;
 
           for (i = 0; i < 9; i++)
               tm_type_elements[i] = &ffi_type_sint;
 
           tm_type_elements[9] = &ffi_type_slong;
           tm_type_elements[10] = &ffi_type_pointer;
           tm_type_elements[11] = NULL;
 
           /* tm_type can now be used to represent tm argument types and
     	 return types for ffi_prep_cif() */
         }

Multiple ABIs

A given platform may provide multiple different ABIs at once. For instance, the x86 platform has both `stdcall' and `fastcall' functions.

`libffi' provides some support for this. However, this is necessarily platform-specific.

The Closure API

`libffi' also provides a way to write a generic function - a function that can accept and decode any combination of arguments. This can be useful when writing an interpreter, or to provide wrappers for arbitrary functions.

This facility is called the „closure API“. Closures are not supported on all platforms; you can check the `FFI_CLOSURES' define to determine whether they are supported on the current platform.

Because closures work by assembling a tiny function at runtime, they require special allocation on platforms that have a non-executable heap. Memory management for closures is handled by a pair of functions:

Function: void *ffi_closure_alloc (size_t SIZE, void **CODE)

Allocate a chunk of memory holding SIZE bytes. This returns a pointer to the writable address, and sets *CODE to the corresponding executable address.

Function: void ffi_closure_free (void *WRITABLE)

Free memory allocated using `ffi_closure_alloc'. The argument is the writable address that was returned.

Once you have allocated the memory for a closure, you must construct a `ffi_cif' describing the function call. Finally you can prepare the closure function:

Function: ffi_status ffi_prep_closure_loc (ffi_closure *CLOSURE, ffi_cif *CIF, void (*FUN) (ffi_cif *CIF, void *RET, void **ARGS, void *USER_DATA), void *USER_DATA, void *CODELOC)

Prepare a closure function.

`ffi_prep_closure_loc' will return `FFI_OK' if everything went ok, and something else on error.

After calling `ffi_prep_closure_loc', you can cast CODELOC to the appropriate pointer-to-function type.

You may see old code referring to `ffi_prep_closure'. This function is deprecated, as it cannot handle the need for separate writable and executable addresses.

Closure Example

A trivial example that creates a new `puts' by binding `fputs' with `stdin'.

     #include <stdio.h>
     #include <ffi.h>
 
     /* Acts like puts with the file given at time of enclosure. */
     void puts_binding(ffi_cif *cif, unsigned int *ret, void* args[],
                       FILE *stream)
     {
       *ret = fputs(*(char **)args[0], stream);
     }
 
     int main()
     {
       ffi_cif cif;
       ffi_type *args[1];
       ffi_closure *closure;
 
       int (*bound_puts)(char *);
       int rc;
 
       /* Allocate closure and bound_puts */
       closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);
 
       if (closure)
         {
           /* Initialize the argument info vectors */
           args[0] = &ffi_type_pointer;
 
           /* Initialize the cif */
           if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
                            &ffi_type_uint, args) == FFI_OK)
             {
               /* Initialize the closure, setting stream to stdout */
               if (ffi_prep_closure_loc(closure, &cif, puts_binding,
                                        stdout, bound_puts) == FFI_OK)
                 {
                   rc = bound_puts("Hello World!");
                   /* rc now holds the result of the call to fputs */
                 }
             }
         }
 
       /* Deallocate both closure, and bound_puts */
       ffi_closure_free(closure);
 
       return 0;
     }

Missing Features

`libffi' is missing a few features. We welcome patches to add support for these.

Note that variadic support is very new and tested on a relatively small number of platforms.