unsafe, FFI & Low-Level Rust

What unsafe allows, calling C functions, raw pointers and volatile access for hardware registers.

Some things the compiler cannot verify: calling C code, dereferencing raw pointers, accessing hardware registers. An unsafe block allows them, and the programmer takes responsibility for safety there. The rest of the program stays checked, and the unsafe parts are small, visible and easy to review.

Calling C and touching raw memory

extern "C" declares functions from the C standard library; calling them is unsafe.

c_strlen is a safe wrapper: it checks for the NUL terminator strlen depends on, so safe code cannot misuse it.

Creating a raw pointer (*mut u32) is safe; dereferencing it is not.

read_volatile/write_volatile prevent the compiler from removing or merging accesses — exactly what memory-mapped registers need (like volatile in C).

The five unsafe superpowers

pub fn get(v: &[u8], i: usize) -> u8 { unsafe { *v.get_unchecked(i) } } pub fn get(v: &[u8], i: usize) -> Option<u8> { v.get(i).copied() }

A public safe function must never allow undefined behaviour for any input. Unchecked access in a safe API lets callers read out of bounds.

Does unsafe turn off the borrow checker?

No. It only enables the five extra operations; all other checks still apply.