liveBook · Manning

Foreign function interface

As explained in Refactoring to Rust

A foreign function interface based on the C calling and binary interface that enables programs in different languages to call C-compatible functions and exchange compatible data.

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.
figure

Shows Rust code presented to an existing application as an ordinary module. section 1.7.1

How Refactoring to Rust covers it

How deep it goes
Explains calling conventions, value exchange, memory sharing, wrappers, linking, strings, and unsafe operations, while deferring detailed techniques.
Examples
Uses Rust libraries called from Python-like applications, Rust embedded in C, cdylib linking, CStr conversion, and raw-pointer wrappers.
What it assumes
Assumes simple Rust programming and introduces cross-language semantics, memory responsibilities, unsafe operations, and C-compatible data exchange.
What you can do after
Build it from scratch by exposing Rust functions to C-compatible callers and containing unsafe boundary code in wrappers.
How it connects
Connects C FFI with memory safety, ownership, unsafe Rust, raw pointers, interpreter bindings, and WebAssembly.

Also explained in

Compare how 2 books explain foreign function interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.