fn use_bare_ptr(ptr: *const i32) {
unsafe {
// 从裸指针读取数据
let value = *ptr;
println!("Value from bare pointer: {}", value);
}
}
fn main() {
let local_variable = 42;
let mut ptr: *const i32;
unsafe {
// 创建指向局部变量的裸指针
ptr = &local_variable as *const i32;
}
// 在unsafe block外部调用函数使用裸指针
use_bare_ptr(ptr);
}
解释
- unsafe块创建裸指针:在
unsafe
块中,我们通过&local_variable as *const i32
将指向局部变量local_variable
的引用转换为裸指针ptr
。这里使用unsafe
块是因为创建裸指针是不安全操作,Rust无法自动管理其生命周期。
- 生命周期管理:
local_variable
的生命周期是从声明开始到main
函数结束。
- 裸指针
ptr
指向local_variable
,只要local_variable
在内存中有效,ptr
就是有效的。在上述代码中,在unsafe
块外部调用use_bare_ptr(ptr)
时,local_variable
仍然在作用域内,所以指针是有效的。
- 函数调用:
use_bare_ptr
函数接受一个裸指针参数,并在其内部的unsafe
块中解引用该指针。这里也需要unsafe
块,因为解引用裸指针是不安全操作。由于我们确保了指针指向的变量在函数调用时仍然有效,所以避免了运行时错误。同时,由于生命周期的正确处理,也避免了编译错误。