Skip to main content
Definition Website Computer and Technology

Foreign Function Interface

Subject: Computer and Technology noun /ˈfɔːr.ən ˈfʌŋk.ʃən ˈɪn.tər.feɪs/ 1 definition

  1. Definition (noun)

    Entry #263 · Updated

    A 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 or cgo preambles 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 ctypes or libffi-based bindings—that load shared libraries dynamically (via dlopen or LoadLibrary) 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) -> u64 into a shared object (libimghash.so) adhering to the System V AMD64 C ABI. At runtime, Python's ctypes module loads libimghash.so via CDLL, passes a POINTER(c_uint8) buffer address and a c_size_t length across the FFI boundary, and receives the c_uint64 digest directly in Python without spawning a separate process.