Libffi Page

libffi



libffi (Foreign Function Interface) is a portable library that allows code written in one language to call functions written in another language. It provides a way to dynamically create calls to functions at runtime, even if the types and number of arguments are not known in advance. libffi is commonly used in language interpreters, foreign language bindings, and other software that needs to interact with code written in different languages.

Key Features


* **Portable:** libffi is designed to work on a wide range of platforms and architectures.
* **Flexible:** libffi can handle a variety of calling conventions and data types.
* **Efficient:** libffi is implemented in a way that minimizes overhead and maximizes performance.
* **Well-tested:** libffi has been used in many projects and is considered to be a stable and reliable library.

Resources


* **Sourceware:** [https://sourceware.org/libffi/](https://sourceware.org/libffi/)
* **GitHub mirror:** [https://github.com/libffi/libffi](https://github.com/libffi/libffi)

Code Example (C)


```c
#include

// Define a function prototype for the function to be called
typedef int (*my_func_t)(int, double);

int main() {
ffi_cif cif;
ffi_type *args[2];
void *values[2];
int arg1 = 42;
double arg2 = 3.14159;
int rc;

// Define the argument types for the function to be called
args[0] = &ffi_type_sint;
args[1] = &ffi_type_double;

// Prepare the call interface
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_sint, args) != FFI_OK) {
// Handle error
return 1;
}

// Set the argument values
values[0] = &arg1;
values[1] = &arg2;

// Call the function
ffi_call(&cif, FFI_FN(my_func_t), &rc, values);

// Use the return value
printf("Result: %d\n", rc);

return 0;
}
```