Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
WebAssembly with Rust: wasm-pack, wasm-bindgen, JS interop, performance optimization and deployment. From Rust code to a running Wasm binary in the browser.
FFI (Foreign Function Interface) lets Rust call functions from other languages — usually C/C++. The common denominator of Rust and C is machine language: to know how Rust values look to C (and vice versa), you must consider their representation in memory.
The good news: Rust and C share many representations:
usize and a C size_t are identicallibc functions like strlen, mallocC is loose about representations
C is surprisingly loose about the sizes of its types: an int is usually 32
bits but could be 16 or more; a char may be signed or unsigned. To cope with
this variance, std::ffi provides Rust types guaranteed to have the same
representation as specific C types — c_int, c_char, c_long, and so on.
Check: What is the common denominator between Rust and C for FFI?
Answer: The representation of values in machine code / memory
Rust and C share memory representations — e.g. usize = size_t, and structs are related. That's what FFI builds on.
⚠ Common mistake: A Rust
structdoes not automatically share its memory layout with its C counterpart —repr(Rust)may reorder fields. Only#[repr(C)]forces the C layout. Pass structs across the FFI boundary without that attribute and the other side reads garbage: the type names match, the offsets don't.
Takeaways:
std::ffi defines Rust types guaranteed to have the same representation as C
types. This protects you from platform-dependent C sizes:
| C type | std::ffi type |
|---|---|
short | c_short |
int | c_int |
long | c_long |
long long | c_longlong |
unsigned / unsigned int | c_uint |
unsigned long | c_ulong |
char | c_char |
signed char | c_schar |
unsigned char | c_uchar |
float / double | c_float / c_double |
void* | c_void |
A C int isn't guaranteed to be 32 bits everywhere. c_int is always what
C int is on this platform. That keeps your FFI portable — and clearly signals
you're talking to C code.
Exception: strings have different names
Besides the numeric types, you also get the string types from std::ffi:
CString (owning) and CStr (borrowed) — null-terminated C stringsOsString / OsStr — system strings (see Module 18)Treating a c_char pointer as a Rust str would be wrong: C strings are
null-terminated byte sequences, not guaranteed valid UTF-8.
Check: Why use c_int instead of i32 in FFI declarations?
Answer: Because c_int is guaranteed to match the C type int on the platform
C int is platform-dependent (usually 32, but not guaranteed). c_int from std::ffi always matches the real C int of the platform and keeps FFI portable.
⚠ Common mistake: Declaring C
longasi32happens to work on Windows and breaks on 64-bit Linux: therec_longis 64 bits wide, and the wrong signature shifts the entire calling convention. Usec_long— thec_types follow the target platform's C compiler, not your assumption.
Takeaways:
An extern block declares functions or variables defined in another library
that will be linked with the final Rust program. Here's how you tell Rust what
C's strlen looks like:
use std::ffi::c_char;
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
// ^ C conventions, ^ unsafe because it has a contract
}
extern "C" = C calling conventions applyunsafe: it requires e.g. a valid, null-terminated string —
a contract Rust cannot enforce.use std::ffi::{c_char, CString};
fn main() {
let rust_str = "I'll be back";
let null_terminated = CString::new(rust_str).unwrap();
unsafe {
assert_eq!(strlen(null_terminated.as_ptr()), 12);
// → no panic: strlen counts 12 bytes up to the null terminator
}
}
CString::new builds a null-terminated C string. It checks for embedded
null bytes (impossible in C strings) and adds the trailing null byte. That's
why the unwrap.
The String → C path
CString::new(str) creates a null-terminated owning string..as_ptr() gives you the *const c_char pointer to it.unsafe).Converting a String (by value) perfectly reuses the existing buffer without a
copy; a &str requires a heap copy.
Check: What does CString::new do on the way to a C function?
Answer: It creates a null-terminated C string and checks for embedded nulls
CString::new builds a null-terminated string, checks for embedded null bytes, and adds the trailing null byte. as_ptr() gives the pointer.
⚠ Common mistake:
strlen(CString::new(s).unwrap().as_ptr())is the classic among FFI bugs: the temporaryCStringis freed at the end of the expression, leaving the pointer aimed at dead memory — and it all compiles without a single warning. Always bind first (let c = CString::new(s)?;), then hand the pointer over inside theunsafeblock.
Takeaways:
If the functions live in a specific library rather than the standard C lib,
you name it with #[link] atop the extern block. Example libgit2:
use std::ffi::c_int;
#[link(name = "git2")]
unsafe extern "C" {
pub fn git_libgit2_init() -> c_int;
pub fn git_libgit2_shutdown() -> c_int;
}
fn main() {
unsafe {
git_libgit2_init();
git_libgit2_shutdown();
}
}
#[link(name = "git2")] tells the linker: bind against libgit2. Behavior
depends on how libgit2 is installed on your system.
Declaring is not defining
The extern block gives Rust the name and type of the function — the
definition is provided later at link time. That's exactly what lets you
work with libraries whose source you don't rewrite in Rust: you only describe
the interface.
Check: What is #[link(name = "git2")] atop an extern block for?
Answer: It names the library the program is linked against
#[link(name = "git2")] tells the linker to link against libgit2. The extern block only describes the interface; the definition comes from the linker.
⚠ Common mistake: Without
#[link(name = "git2")]or acargo:rustc-link-libfrom yourbuild.rs, only linking fails:undefined reference to 'git_libgit2_init'. Rust compiles theexternblock itself without complaint — whether the library exists is checked by the linker, not rustc. And the name follows the linker convention: "git2", not "libgit2.so".
Takeaways:
Raw FFI calls are unsafe and tedious. The art is encapsulating them in a
safe interface: the inside is unsafe, the public API is safe and offers a
contract.
struct Calculator;
impl Calculator {
// SAFETY: libc::strlen is valid because we pass a null-terminated string.
fn text_length(text: &str) -> usize {
let c = std::ffi::CString::new(text).expect("no \\0 allowed");
unsafe { strlen(c.as_ptr()) }
// → text_length("hello") yields 5
}
}
From outside you call Calculator::text_length("hello") — safe, without
unsafe, and with guaranteed correct usage.
A safe wrapper function must:
unsafe to the inside and justify each occurrence with
// SAFETY:git_libgit2_init() returns a c_int status — your
wrapper turns it into a Result or panic!Drop to call e.g. git_libgit2_shutdown()
automaticallyBound FFI like Unsafe
The same strategy as Module 20: hide small amounts of unsafe behind safe interfaces. So caller code stays fully safe, and all the unpleasant contracts (pointers, null-termination, C status codes) live in one clearly marked place.
Check: What is the goal of a safe FFI wrapper?
Answer: Confine unsafe calls and offer a safe API with a contract
The wrapper keeps raw FFI calls inside (with // SAFETY justification) and offers a safe public function that guarantees contracts like null-termination.
⚠ Common mistake: Ignoring the
c_intreturn value ofgit_libgit2_init()takes away C's only error report: a failed init then looks like a success, and the service crashes much later in an unrelated place. The wrapper should check the status code and turn it into aResultor apanic!— that is exactly what it is for.
Takeaways:
Many popular Rust crates are thin safe wrappers around C libraries:
git2 — a safe wrapper around libgit2 (Git in Rust)openssl / ring — cryptography APIs (OpenSSL / C)rusqlite — a safe wrapper around SQLitelibc — direct access to the C standard libraryThese crates work on the pattern from Lesson 5: unsafe FFI inside, a safe, idiomatic Rust API outside.
┌────────────────────────────────────────┐
│ Rust application (safe, idiomatic) │
├────────────────────────────────────────┤
│ git2 / rusqlite (safe wrapper) │
├────────────────────────────────────────┤
│ extern blocks + #[link] (unsafe FFI) │
├────────────────────────────────────────┤
│ libgit2 / SQLite (C library) │
└────────────────────────────────────────┘
Each layer encapsulates the discomfort below and offers a more convenient, safer interface upward.
Automated C-to-Rust translation with formal equivalence
The tool cozy (2026) uses comparative symbolic execution to automatically translate C code to Rust — and proves that both versions behave identically. Outside the flagged differences, the binaries are formally verified to be equivalent. The developer assesses each difference as intentional (good) or erroneous (bad).
This means FFI is not the only bridge between C and Rust. Where a full translation is feasible, formal verification can guarantee the safety that a manual port cannot.
FFI vs. pure-Rust crates
Use FFI when a mature C library exists (SQLite, OpenSSL) — you needn't rewrite everything. Prefer pure-Rust crates when an equivalent exists: they're more portable, need no system linking, and share Rust's safety and side-effect guarantees. FFI is the bridge when there's no reasonable pure-Rust alternative.
Check: Why often prefer a pure-Rust crate over FFI?
Answer: It's more portable, without system linking, with Rust safety guarantees
Pure-Rust crates need no external linking, run anywhere, and share Rust's safety model. FFI is the choice when no equivalent pure-Rust alternative exists.
⚠ Common mistake: Hand-writing your own
externdeclarations for libgit2 or SQLite whengit2orrusqliteexist means taking over every contract yourself — every signature, every status code, every deallocation. The existing crates have already done and tested exactly that work. Custom bindings pay off only when there really is no wrapper crate.
Takeaways:
You build a safe Rust API around C's strlen — it tests the core FFI concepts
of this module:
strlen(s: *const c_char) -> usize in an unsafe extern "C" block
(import c_char from std::ffi).text_length(text: &str) -> usize that internally
uses CString::new + unsafe { strlen(...) }, with a // SAFETY:
comment.&str argument — without main itself touching unsafe.This links: extern blocks, std::ffi types, CString, unsafe reasoning, and
the safe-wrapper pattern from Lesson 5.
Recipes from this module
unsafe extern "C" { fn strlen(s: *const c_char) -> usize; }std::ffi::{c_char, c_int, c_void, CString}CString::new(text)? then .as_ptr()fn, inside unsafe { ... } with // SAFETY:#[link(name = "git2")] for foreign librariesScenario: The old library
⚠ Common mistake: Declaring the wrapper as
pub unsafe fn text_length(...)misses the point of the exercise: every caller then needs their ownunsafeblock again and must justify the contract themselves. The public function must be safe —unsafebelongs inside, together with a// SAFETY:comment.
Takeaways:
Course navigation: ← Module 20 · All 27 modules · Module 22 →