A foreign function interface lets programs in different languages communicate through functions that follow C calling conventions, parameter passing, return-value rules, and mutually representable types. It supports incremental refactoring by embedding Rust in an existing application while keeping both sides in one process and potentially sharing memory directly. section 3.0 section 1.7.1
Common integration choices differ in reach, convenience, and memory responsibility:
- Use C FFI for broad language compatibility, especially when integrating with C or C++; accept direct responsibility for allocation, deallocation, transfer, and ownership. section 1.7.1
- Bind directly to a language interpreter for an interface resembling Python, Ruby, or Node.js libraries; implementation depends on available Rust bindings. section 1.7.1
- Use WebAssembly FFI when integrating Rust with browser JavaScript engines or Node.js. section 1.7.1
Embedding Rust in C
Place business logic in an ordinary Rust function and expose a wrapper with FFI-compatible annotations. Build the Rust code as a cdylib, link it with the C program, and use CStr when converting null-terminated C strings into Rust string slices. Unsafe blocks may handle raw pointers, while safe Rust abstractions contain the rest of the logic. section 3.3 section 3.0
Figure 1.3 When calling Rust directly from your existing application, your Rust code looks like a normal module.
Shows Rust code presented to an existing application as an ordinary module. section 1.7.1

