Concept

Foreign Function Interface

A foreign function interface lets code in one language call functions, load libraries, exchange data, or expose callable APIs across language and runtime boundaries.

What FFI Solves

Foreign function interfaces let programs cross language boundaries. A Rust library can call C APIs. Go can use cgo to call C code. Python can load shared libraries through ctypes. Java can use JNI. .NET exposes native interop features for platform libraries and native components.

FFI is important because real systems rarely live in one language forever. Operating systems, databases, compression libraries, graphics APIs, numerical kernels, device SDKs, and legacy libraries often expose C or C-compatible interfaces even when the application language is higher level.

Handwritten assembly can participate in the same boundary, but it normally does so at the ABI level rather than through a language-level FFI wrapper. An assembly routine called from C, Rust, Python extension code, Java JNI glue, or .NET native interop must obey the target calling convention, stack alignment, register preservation, symbol, relocation, and unwind rules.

Boundary Costs

The boundary is usually where the safety model changes. The caller and callee must agree on layout, ownership, allocation, lifetimes, strings, exceptions, callbacks, thread attachment, error reporting, and who may free which resource.

Crossing the boundary can also affect build systems and deployment. A package may need headers, link flags, dynamic libraries, platform SDKs, generated bindings, architecture-specific artifacts, or runtime loader configuration.

Good FFI Design

Good FFI wrappers keep the unsafe or runtime-specific edge narrow. They translate raw handles into safer types, document ownership, isolate platform-specific code, test error paths, and avoid leaking foreign invariants into the whole application.

When possible, prefer a small C-compatible surface over exposing complex language-specific objects directly. Stable C ABIs are often the least surprising interoperability layer, even when neither side is written primarily in C.

Related Concepts

FFI belongs with ABI Stability, Manual Memory Management, Ownership, Compilation Targets, and Build Systems.

Sources

Last verified:

  1. x86-64 psABI x86 psABI maintainers
  2. The Rust Reference - External blocks Rust Project
  3. cgo command Go Project
  4. ctypes - A foreign function library for Python Python Software Foundation
  5. Java Native Interface Specification Oracle
  6. Native interoperability Microsoft Learn