Foreign Function Interface
Subject: Computer and Technology noun /ˈfɔːr.ən ˈfʌŋk.ʃən ˈɪn.tər.feɪs/ 1 definition
- programming-languages
- systems-programming
- compiler-design
- software-engineering
-
Definition (noun)
Entry #263 · UpdatedA Foreign Function Interface (FFI) is a programming language mechanism that allows software written in one language (the host language) to call routines and exchange data with libraries implemented in another language (the guest language). Because languages differ in type representations, memory layouts, and calling conventions, an FFI bridges the runtime boundary over a shared Application Binary Interface (ABI)—most commonly the platform's C ABI—by marshaling arguments, converting return values, and coordinating memory ownership or garbage-collection pinning. Unlike inter-process communication (IPC) or network APIs, an FFI operates within the same process address space, enabling low-overhead reuse of mature native libraries, direct operating system calls, and delegation of compute-intensive workloads to systems languages such as C, C++, or Rust. Because invocations across an FFI boundary typically bypass the host runtime's compile-time type checks and memory safety guarantees, mismatched struct alignments, dangling pointers, or uncaught exceptions can cause undefined behavior or process crashes.
Common Forms
Static ABI Declarations: Language-level linkage directives and type annotations—such as
extern "C"blocks in Rust orcgopreambles in Go—that instruct the compiler to emit machine calls matching a target library's binary calling convention at compile time.Dynamic Runtime FFI: Runtime libraries—such as Python's
ctypesorlibffi-based bindings—that load shared libraries dynamically (viadlopenorLoadLibrary) and construct call frames at runtime without ahead-of-time compiled glue code.Binding Generators: Code-generation tools such as SWIG, Rust
bindgen, or Cython that parse C or C++ header files to automatically emit type-checked wrapper functions and struct definitions in the host language.Managed Runtime Native Interfaces: Dedicated runtime C APIs—such as the Java Native Interface (JNI) or the CPython C API—that give compiled native extensions controlled access to managed heap objects, garbage-collector handles, and runtime exception states.
Example
To accelerate image hashing in a Python web service, a developer compiles a Rust library exporting
#[no_mangle] pub extern "C" fn hash_frame(ptr: *const u8, len: usize) -> u64into a shared object (libimghash.so) adhering to the System V AMD64 C ABI. At runtime, Python'sctypesmodule loadslibimghash.soviaCDLL, passes aPOINTER(c_uint8)buffer address and ac_size_tlength across the FFI boundary, and receives thec_uint64digest directly in Python without spawning a separate process.