liveBook · Manning

C bindings

As explained in Refactoring to Rust

A Rust binding is interface metadata and declarations that expose the functions, types, and global variables of a foreign-language library to Rust code.

C bindings expose a foreign library’s functions, types, and global variables to Rust as declarations and interface metadata, without including their implementations. They let Rust code cross the C FFI boundary and call libraries such as NGINX or OpenSSL. section 4.3

A typical binding workflow is:

  • Create a C wrapper header that includes the foreign library headers required by the Rust integration. section 4.3.2
  • Use bindgen from a Cargo build dependency and build script to parse declarations and generate compatible Rust code. section 4.3.2
  • Restrict generated items with filters such as ngx_ prefixes to reduce unnecessary API surface and compilation cost. section 4.3.2
  • Write generated bindings to the build output directory and include them with OUT_DIR before defining the Rust FFI function. section 4.3.2

Binding NGINX types

A Rust NGINX handler can include generated declarations, use ngx_http_request_t and ngx_int_t, and expose an unsafe extern "C" function with #[no_mangle]. The resulting dynamic library is linked into NGINX, which can then load the module and invoke the handler. section 4.3 section 4.3.2

Figure 4.1 High- and low-level Rust bindings for the openssl C library
figure

Shows the relationship between high-level Rust bindings, low-level generated bindings, and the OpenSSL C library. section 4.3

How Refactoring to Rust covers it

How deep it goes
Explains metadata, generation, filtering, inclusion, and linking, while stopping short of implementing foreign-library functions.
Examples
Demonstrates NGINX header parsing, generated ngx_ declarations, an extern C handler, and layered OpenSSL bindings.
What it assumes
Assumes familiarity with C headers and Rust projects while teaching the binding-generation process incrementally.
What you can do after
Build it from scratch using bindgen, a wrapper header, a build script, generated Rust declarations, and an FFI entry point.
How it connects
Connects C FFI, bindgen, build scripts, unsafe Rust, dynamic libraries, NGINX modules, and OpenSSL.

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.