ptr::slice_from_raw_parts() 函数

ptr::slice_from_raw_parts() 以及 ptr::slice_from_raw_parts_mut() 函数用于手动构造切片引用. 它们的函数接口如下:

#![allow(unused)]
fn main() {
pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T];
pub fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T];
}

用法也比较简单, 看一个示例:

use std::{mem, ptr};

fn main() {
    let numbers = [1, 1, 2, 3, 5, 8];
    let len: usize = numbers.len();
    let num_ptr: *const i32 = numbers.as_ptr();
    let num_raw_ref: *const [i32] = ptr::slice_from_raw_parts(num_ptr, len);
    let num_ref: &[i32] = unsafe {
        &*num_raw_ref
    };
    assert_eq!(num_ref, [1, 1, 2, 3, 5, 8]);

    let num_ref2: &[i32] = unsafe { mem::transmute::<(*const i32, usize), &[i32]>((num_ptr, len)) };
    assert_eq!(num_ref, num_ref2);
}

上面的代码中展示了两种构造切片引用的方法:

  • ptr::slice_from_raw_parts(num_ptr, len);
  • unsafe { mem::transmute::<(*const i32, usize), &[i32]>((num_ptr, len)) }