capypad
0 day streak
rust / intermediate
Snippet

Unsafe Rust: Raw Pointers and FFI

Unsafe Rust unlocks five extra abilities: raw pointer dereferencing, calling unsafe functions, accessing mutable statics, implementing external traits, and accessing mutable references in inline assembly. The unsafe block tells the compiler 'I promise this is safe.'

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn main() {
let mut values = [1, 2, 3, 4, 5];
let ptr = values.as_mut_ptr();
let len = values.len();
let capacity = values.capacity();
 
unsafe {
for i in 0..len {
*ptr.add(i) *= 2;
}
println!("Doubled via raw pointer: {:?}", values);
}
 
extern "C" {
fn abs(input: i32) -> i32;
}
 
let negative = -42;
let absolute = unsafe { abs(negative) };
println!("Absolute value of {}: {}", negative, absolute);
 
unsafe fn dangerous_operation() -> i32 {
println!("This function is unsafe!");
42
}
 
let result = unsafe { dangerous_operation() };
println!("Unsafe function result: {}", result);
}
Breakdown
1
values.as_mut_ptr()
Gets raw mutable pointer; no lifetime tracking
2
*ptr.add(i) *= 2
Dereferences and modifies; requires unsafe block
3
extern "C" { fn abs }
FFI declaration; calls C standard library function
4
unsafe fn dangerous_operation()
Function marked unsafe; caller must use unsafe block
5
unsafe { abs(...) }
Calling unsafe extern function requires unsafe block