liveBook · Manning

Extern "C"

As explained in Refactoring to Rust

extern "C" is a Rust function annotation that gives a function the C ABI and makes it callable according to C conventions.

extern "C" gives a Rust function C calling conventions so C code can call it across an FFI boundary. A named C entry point also needs pub and #[no_mangle], while a callback passed by address needs only extern "C". section 4.4

Use the annotation according to how the function crosses the boundary:

  • Mark an exported handler as pub unsafe extern "C" and #[no_mangle} when C calls it by name. section 4.4
  • Mark a callback as unsafe extern "C" when C supplies or invokes it through a function pointer. section 4.4
  • Omit extern "C" for functions called only by Rust; they retain Rust calling conventions and are not callable from C. section 4.4

NGINX request callback

unsafe extern "C" fn read_body_handler(r: *mut ngx_http_request_t) { ... }

How Refactoring to Rust covers it

How deep it goes
Explains calling conventions and annotation combinations, then demonstrates handlers and function-pointer types without detailing ABI internals.
Examples
Uses an NGINX request handler, a request-body callback, and a Rust-only request-body conversion helper.
What it assumes
Assumes basic Rust functions and C declarations while introducing FFI signatures, exported symbols, and callback conventions incrementally.
What you can do after
Apply it to declare Rust functions callable from C and to type callbacks passed through C APIs.
How it connects
Ties C calling conventions to FFI, name mangling, visibility, unsafe functions, callbacks, and function pointers.

Also explained in

Compare how 2 books explain extern "C" →

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.