Rust Unsafe Code — Unsafe Blocks, Raw Pointers, and FFI with C Code
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Unsafe Code. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust unsafe code enables raw pointer dereference, FFI calls, inline assembly, and mutable static variables within unsafe blocks.
What You'll Learn
- Unsafe blocks
- Raw pointers
- FFI with C
- Union and inline assembly
Why It Matters
Unsafe code interfaces with hardware and C libraries. DodaZIP uses FFI for system compression libraries.
Real-World Use
OS kernel development, custom allocators, C library bindings, hardware drivers.
use std::ffi::{CString, CStr};
use std::os::raw::c_char;
// Raw pointers
fn raw_pointer_example() {
let x = 42;
let raw_ptr: *const i32 = &x as *const i32;
unsafe {
println!("Raw pointer value: {}", *raw_ptr);
}
let mut y = 10;
let raw_mut: *mut i32 = &mut y as *mut i32;
unsafe {
*raw_mut = 20;
}
println!("Modified: {}", y);
}
// FFI with C
extern "C" {
fn strlen(s: *const c_char) -> usize;
fn puts(s: *const c_char) -> i32;
}
fn ffi_example() {
let rust_string = "Hello from Rust!";
let c_string = CString::new(rust_string).unwrap();
unsafe {
let len = strlen(c_string.as_ptr());
println!("C string length: {}", len);
puts(c_string.as_ptr());
}
}
// Unsafe function
unsafe fn dangerous() {
println!("This is unsafe!");
}
fn main() {
unsafe {
dangerous();
}
raw_pointer_example();
// ffi_example(); // Needs linking with libc
}
← Previous
Rust Macros — Declarative Macros with macro_rules! and Procedural Macros
Next →
Rust Testing Advanced — Integration Tests, Benchmarks, Property-Based Testing, and Mocking
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro