问题
当原始指针作为一个safe函数的结果时,由于safe不能解引用,因此使用起来不方便。
原始指针转为引用
可以将其转化为引用,这样就不需要unsafe也能使用该数据。当然也可以通过指定生命周期参数(或自动推导)来创建非static的引用。
核心思想就是使用unsafe来获取指针指向的数据的左值,然后对其取引用。这样的左值不会被Borrow checker管理。
下面例子取自rCore。
例子的get_current_mem_set
中,先获取了result的可变原始指针,然后在unsafe里面重新获取其左值并且进行static的可变引用。这样就实现了“对一个局部变量进行static的可变引用”。这种引用的功能是最强的,没有任何使用限制。
例子的get_ref
中,addr是一个简单的数值,是一个地址的值。先将其转为*const T
,即指向类型T的不可变指针;这样就能通过*(addr as *const T)
得到类型T的数据(左值),对其取引用就得到了其不可变引用。
fn get_current_mem_set(&self) -> &'static mut MemorySet {
...
let result: MemorySet = ...;
let ptr = &mut result as *mut MemorySet;
unsafe{&mut *ptr}
}
pub fn get_ref<T>(&self, offset: usize) -> &T where T: Sized {
...
let addr = self.addr_of_offset(offset);
unsafe { &*(addr as *const T) }
}
原始指针和Box互相转换
官方提供了转换的函数,不过Safety依然需要手动管理。
/// # Safety
///
/// The `ptr` must contain an owned box of `Foo`.
unsafe fn raw_pointer_to_box(ptr: *mut Foo) -> Box<Foo> {
// SAFETY: The `ptr` contains an owned box of `Foo` by contract. We
// simply reconstruct the box from that pointer.
let mut ret: Box<Foo> = unsafe { Box::from_raw(ptr) };
ret.b = Some("hello".to_owned());
ret
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn test_success() {
let data = Box::new(Foo { a: 1, b: None });
let ptr_1 = &data.a as *const u128 as usize;
// SAFETY: We pass an owned box of `Foo`.
let ret = unsafe { raw_pointer_to_box(Box::into_raw(data)) };
let ptr_2 = &ret.a as *const u128 as usize;
assert!(ptr_1 == ptr_2);
assert!(ret.b == Some("hello".to_owned()));
}
}