何时将函数标记为unsafe仅使用unsafe块?我在阅读另一个答案时看到了这个功能:
unsafe fn as_u8_slice(xs: &[i32]) -> &[u8] {
std::slice::from_raw_parts(v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<i32>())
}
Run Code Online (Sandbox Code Playgroud)
我可能会把这个函数写成:
fn as_u8_slice(xs: &[i32]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<i32>())
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,我觉得在所有情况下调用函数都是安全的,但编译器无法验证函数内部的功能.但是,我没有任何关于何时适合使用其中一个的规则.
我正在为 C 库编写一个包装器,但我一直在编写大量类型,例如CVecOf<anything>:
#[repr(C)]
pub struct CVecOfPoint {
pub array: *mut Point2i,
pub size: usize,
}
impl CVecOfPoint {
pub fn rustify(&self) -> Vec<Point2i> {
(0..self.size)
.map(|i| unsafe { *(self.array.offset(i as isize)) })
.collect::<Vec<_>>()
}
}
#[repr(C)]
pub struct CVecOfPoints {
pub array: *mut CVecOfPoint,
pub size: usize,
}
impl CVecOfPoints {
pub fn rustify(&self) -> Vec<Vec<Point2i>> {
(0..self.size)
.map(|i| unsafe {
let vec = &*self.array.offset(i as isize);
vec.rustify()
})
.collect::<Vec<_>>()
}
}
pub struct CVecOfPointsOfPoints;
pub struct …Run Code Online (Sandbox Code Playgroud)