FFI

As a systems language, Rust is able to interact with other programming languages with zero extra overhead. This point of interaction is referred to as the Foreign Function Interface, where the term "foreign function" refers to functions that the compiler has no way of inspecting (e.g. because it's from a DLL written in another language).

At the moment, Rust only supports FFI through the C ABI, as that is the most common and stable ABI in existence, and it allows Rust to interact with almost all libraries. In the future, Rust may support other ABIs such as the Swift ABI, and it may even get its own stable ABI.

Declaring the Existence of Foreign Functions
Before code can call external functions, declarations need to be created so the compiler knows about the functions and their signatures. In Rust this is done using  blocks.

For example, to declare an  function which accepts two integers and returns an integer you would write a declaration like this:

Extern functions in Rust also support variadic arguments (an unspecified number of arguments of any type), as used in C functions such as :

Declarations like these can be automatically generated from C headers using.

You can instruct the Rust compiler to link against certain static or dynamic libraries using the  attribute:

Calling Foreign Functions
By definition a foreign function contains code that the Rust compiler is unable to read or analyse, making it impossible for the borrow checker to ensure it is following Rust's rules around ownership, lifetimes, and borrowing. That means any code calling a foreign function must be done from an  block.

For example, to call the previous  function:

This requirement to use  means FFI and unsafe are closely related, with a lot of conceptual overlap.