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
define to determine whether they are supported on the current
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:
Allocate a chunk of memory holding size bytes. This returns a pointer to the writable address, and sets *code to the corresponding executable address.
size should be sufficient to hold a
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:
Prepare a closure function.
closure is the address of a
ffi_closure object; this is
the writable address returned by
cif is the
ffi_cif describing the function parameters.
user_data is an arbitrary datum that is passed, uninterpreted, to your closure function.
codeloc is the executable address returned by
fun is the function which will be called when the closure is invoked. It is called with the arguments:
ffi_cif passed to
A pointer to the memory used for the function’s return value.
fun must fill this, unless the function is declared as returning
A vector of pointers to memory holding the arguments to the function.
The same user_data that was passed to
ffi_prep_closure_loc will return
FFI_OK if everything
went ok, and something else on error.
ffi_prep_closure_loc, you can cast codeloc
to the appropriate pointer-to-function type.
You may see old code referring to
function is deprecated, as it cannot handle the need for separate
writable and executable addresses.