Foreign Function Interface (FFI): Calling Other Languages
Think of an FFI as a universal adapter, letting your program call functions written in another language. It's how modern code in Rust or Go can reuse battle-tested C libraries for tasks like graphics or system calls, avoiding a complete rewrite.
WHY IT EXISTS No single programming language is perfect for every task. Often, decades of work have gone into creating stable, high-performance libraries in languages like C or C++. FFI exists to prevent rewriting the world; it lets you reuse this valuable, battle-tested code from a different host language.
THE MENTAL MODEL An FFI is a contract or a translation layer between two languages. Imagine it as a diplomat translating between two leaders who don't speak the same language. The diplomat (the FFI) ensures that when one language passes an 'integer' or a 'string', the other language understands its memory layout and calling convention. It's the bridge that makes interoperability possible.
HOW IT WORKS A developer defines a "binding" in the host language that mirrors the function signature in the foreign language. For example, in Rust, you'd use an extern "C" block to declare the name, arguments, and return type of a C function. When you call this function, the FFI layer handles marshalling the data—converting your language's types (like a Rust String) into a format the foreign code understands (like a null-terminated C char*). It then invokes the function from the binary or dynamic-link library and marshals the return value back.
WHEN TO USE IT Use FFI when you need to integrate with existing C/C++ libraries that would be too costly to rewrite, such as SQLite, OpenSSL, or a physics engine. It's also necessary for calling operating system APIs that are only exposed through a C interface. Finally, it allows writing performance-critical sections of an application in a low-level language and calling them from a higher-level one.
WHEN NOT TO USE IT Avoid FFI for simple logic that can be easily rewritten. The complexity and safety risks are often not worth it. If the boundary between the two languages is very "chatty" (many frequent, small calls), the overhead of marshalling data back and forth can become a performance bottleneck. It's best for coarse-grained interactions.
ONE CANONICAL EXAMPLE A common use is a Go or Rust application needing to interact with a GUI toolkit written in C++, like Qt. Instead of rewriting the entire UI library, the application uses FFI to call functions like create_window() or add_button() from the compiled C++ library. The FFI layer translates the Go/Rust function calls and data into their C++ equivalents, allowing the two parts of the system to work together.
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.