A foreign function interface (FFI) is a mechanism that allows a program written in one programming language to call functions or use services implemented in another language. It provides interoperability across language boundaries by reconciling differences in function calls, data representation, memory management, and runtime behavior. A common use is allowing a high-level language to invoke libraries exposed through the C calling interface, although FFIs are not limited to C.
Scope and related interfaces
An FFI connects language environments, whereas an application programming interface (API) describes the operations that software exposes to its users. A library can have a C API and separate bindings that make the same operations available in Python, Java, or another language. Those bindings may rely on an FFI internally.
An application binary interface (ABI) defines lower-level conventions that separately compiled components must follow, including argument passing, return values, register use, and aspects of data layout. An FFI often uses an existing ABI but also handles language-level differences that the ABI alone does not resolve, such as converting strings or tracking object lifetimes.
FFI calls usually occur within a single process, where the participating components share an address space. This distinguishes them from interprocess communication and remote service calls, which cross process boundaries. Some interoperability systems combine these approaches, but an FFI is not inherently a network or messaging protocol.
“Foreign” is relative to the calling language or runtime. It does not imply that the called function runs on another computer or comes from an external organization.
How an FFI works
A typical foreign call involves several steps:
- Describe the function. The caller supplies or obtains a declaration specifying the function’s name, parameter types, return type, and calling convention.
- Locate the implementation. The function is resolved during linking or obtained from a library loaded at runtime.
- Prepare arguments. Values are converted, copied, or represented in forms the called function understands.
- Perform the call. Compiler-generated code or a runtime helper transfers control according to the target ABI.
- Handle the result. The returned value, error information, and any transferred resources are translated into the caller’s conventions.
Some FFIs perform much of this work at compile time. Others interpret function descriptions at runtime. A compiler may generate a direct native call when the relevant types and conventions are known, while an interpreter or runtime library may construct the call dynamically.
Calling conventions and binary compatibility
A calling convention determines details such as which arguments occupy registers, which are placed on the call stack, and how the return value is delivered. A mismatch can produce incorrect results or memory corruption even when the function name is resolved successfully.
Data layout matters as well. The width of an integer, the alignment of a structure, and the representation of a Boolean value can differ across languages or platforms. Structure padding and the rules for passing or returning aggregates must match the ABI.
C is a common interoperability boundary because its interfaces can be expressed in terms of relatively simple functions, scalar values, pointers, and structures, and because C-compatible toolchains are widely available. This does not make the C ABI universal: conventions differ among processor architectures, operating systems, and toolchains.
C++ interoperability is often more complicated because of name mangling, classes, templates, exceptions, and compiler-specific binary conventions. A common approach is to place a C-compatible wrapper around C++ functionality. Such a wrapper exposes a simpler boundary without making C++ object representations portable.
Data conversion and marshalling
The preparation of values for transfer across an interface is often called marshalling. Some values can pass directly; others require substantial transformation.
Common issues include:
- Numbers: Integer widths, signedness, floating-point formats, and conversion behavior must agree.
- Strings: A language-level string may need conversion to a null-terminated byte sequence or a pointer accompanied by a length. Unicode support does not by itself establish a shared encoding.
- Arrays: The interface must specify element type, length, layout, and whether the callee may modify or retain the storage.
- Records: Fields must match in order, size, alignment, and padding.
- Objects: Runtime-managed objects may need to be represented by opaque handles rather than exposed directly.
- Pointers: An address is useful only when its target remains valid and the receiving code understands what it points to.
An FFI therefore bridges semantic differences as well as binary ones. A pointer to bytes, for example, does not independently specify whether the bytes represent text, which encoding they use, or who owns the memory.
Memory management and runtime interaction
Ownership and lifetime
One of the most important parts of an FFI contract is specifying who owns each resource and when it may be released. Memory allocated by a foreign library may need to be freed through that library’s own deallocation function rather than through the caller’s allocator.
A managed runtime using garbage collection introduces additional requirements. The collector may need to know that foreign code still holds a reference to an object. If the collector can move objects, an FFI may pin an object in place, copy its contents, or expose a stable handle instead of a raw address.
Ownership mistakes can cause memory leaks, double frees, or use-after-free errors. A function declaration alone rarely conveys all the necessary lifetime rules; these often appear in documentation or binding annotations.
Callbacks and reentrancy
A callback allows foreign code to invoke a function supplied by the caller. For example, a native library may call a comparison function implemented in another language.
An FFI may construct a small adapter, sometimes called a trampoline, that receives a native call and enters the destination runtime. The callback object and its associated state must remain alive for as long as the foreign library might invoke it.
Callbacks also introduce reentrancy: foreign code can call back into a runtime while an earlier foreign call is still active. This can affect locking, runtime state, and the validity of assumptions made before the original call.
Threads and blocking operations
Foreign libraries may create threads or invoke callbacks on threads unknown to the host runtime. Some runtimes require those threads to be attached or registered before they can access managed objects.
Long-running native calls can also interact with runtime scheduling. An FFI may provide mechanisms to release a runtime lock, identify a potentially blocking call, or coordinate garbage collection. Incorrect assumptions at this boundary can contribute to a race condition or deadlock.
Errors and exceptions
Languages represent failure differently. A C API may use a status code, a null pointer, or thread-local error state, while another language uses exceptions.
Bindings often translate these representations explicitly. Exception propagation across a foreign boundary requires specific support; it cannot generally be assumed safe. Interfaces that do not support cross-language unwinding commonly catch exceptions before they leave one runtime and convert them into a documented error representation.
Implementation approaches
FFI implementations commonly use one or more of the following approaches:
- Compiler-supported declarations. Foreign functions and calling conventions are declared in source code, enabling compile-time checking and native call generation.
- Runtime call interfaces. A runtime library constructs calls from descriptions of argument and return types. The libffi library provides this kind of low-level machinery; it does not by itself supply complete language bindings.
- Generated bindings. Tools read declarations or interface descriptions and generate wrappers. Generation reduces repetitive work but does not automatically resolve ownership or semantic ambiguities.
- Handwritten adapters. Custom wrappers translate complex objects, enforce invariants, and present an interface suited to the calling language.
A binding is usually broader than the underlying FFI mechanism. It can include constants, object wrappers, resource-management rules, and language-specific conveniences. A technically correct binding may still expose an awkward interface if it merely reproduces the foreign library’s conventions.
Examples
Python provides ctypes for calling functions in shared libraries using declared native types. CPython also exposes a C API for building extension modules. These approaches differ in how much adapter code is written in Python or C.
Java’s Java Native Interface supports interaction between native code and the Java virtual machine. Rust supports foreign declarations and C-compatible interfaces; foreign calls commonly require an explicit unsafe boundary, around which a binding can build a more restricted safe interface.
A small C API illustrates why types alone are insufficient:
struct image;
struct image *image_open(const char *path);
int image_width(const struct image *img);
void image_close(struct image *img);
A binding must establish more than the signatures. It needs to know the path encoding, what signals failure, whether image_open retains the path, whether operations are thread-safe, and whether every successfully opened image requires exactly one call to image_close.
The opaque struct image pointer lets the library hide its internal representation. A higher-level wrapper can associate that pointer with automatic cleanup while preventing operations after the image has been closed.
Uses, performance, and limitations
FFIs support reuse of existing libraries, incremental migration between languages, integration with platform APIs, and access to specialized native code. Scientific software frequently combines high-level orchestration with compiled numerical routines. Machine-learning systems similarly use language bindings to reach native computation libraries and hardware-specific implementations.
A foreign call is not necessarily expensive, but its cost depends on the implementation and workload. Direct calls between compatible native components may have little overhead. Runtime transitions, argument checking, allocation, string conversion, and copying can make other calls substantially more costly. Many fine-grained calls may therefore cost more than a batched operation performing equivalent work.
FFIs also inherit the constraints of the target interface. Variadic functions, complex native object models, asynchronous callbacks, and platform-specific data layouts can make bindings difficult to implement or maintain. A library update may preserve source compatibility while breaking binary compatibility, or preserve signatures while changing assumptions on which a binding relies.
Safety and isolation
An FFI commonly weakens the guarantees of the calling language’s type system and memory-management model. A language with bounds-checked arrays cannot necessarily prevent native code from overrunning a buffer. Incorrect declarations or unsafe native implementations can introduce a buffer overflow or another security vulnerability into an otherwise memory-safe application.
Safe wrappers can narrow this boundary by checking lengths, restricting pointer access, encoding ownership, and translating errors. Their guarantees still depend on the correctness of the underlying foreign implementation and its documented contract.
An FFI is not inherently a sandbox. Native code running in the same process generally has access to that process’s memory and privileges. Where isolation is required, a separate process with a constrained communication interface provides a different security boundary, at the cost of communication overhead and more explicit data exchange.