如何获得下一个指针?

时间:2017-05-01 19:32:52

标签: rust raw-pointer

我有一个用C实现的函数,我想在Rust中用相同的接口编写一个函数。该函数接收指向数组开头(win8_t *)的指针和数组的长度。我需要能够运行数组。

必须有更好的方法来获得下一个值,但现在我可以做这个奇怪的事情:

use std::mem;
pub extern "C" fn print_next(i: *const u8) {
    let mut ii = unsafe { mem::transmute::<*const u8, i64>(i) };
    ii += 1;
    let iii = unsafe { mem::transmute::<i64, *const u8>(ii) };
    let jj = unsafe { *iii };
    println!("{}", jj); // jj is next value
}

1 个答案:

答案 0 :(得分:2)

正如Shepmaster所说,你可能需要提供切片的长度。

大多数时候你使用指针,你的功能将是不安全的(因为你通常需要在某些时候取消引用它)。将安全责任委托给调用者可能是不安全的标记。

以下是使用offsetfrom_raw_slice的一些示例:

use std::mem;
use std::slice;

// unsafe!
pub extern "C" fn print_next(i: *const u8) {
    let mut ii = unsafe { mem::transmute::<*const u8, i64>(i) };
    ii += 1;
    let iii = unsafe { mem::transmute::<i64, *const u8>(ii) };
    let jj = unsafe { *iii };
    println!("{}", jj); // jj is next value
}

// unsafe!
pub unsafe extern "C" fn print_next2(i: *const u8) {
    let j = *i.offset(1);
    println!("{}", j);
}

// (less but still ...) unsafe!
pub unsafe extern "C" fn print_next3(i: *const u8, len: usize) {
    let slice = slice::from_raw_parts(i, len);
    // we are not checking the size ... so it may panic!
    println!("{}", slice[1]);
}

fn main() {
    let a = [9u8, 4, 6, 7];
    print_next(&a as *const u8);
    unsafe {
        print_next2(&a[1] as *const u8);
        print_next3(&a[2] as *const u8, 2);
    }

    // what if I print something not in a??
    print_next(&a[3] as *const u8); // BAD
    unsafe { 
        print_next2(&a[3] as *const u8); // BAD
        print_next3(&a[3] as *const u8, 2); // as bad as others, length is wrong

        print_next3(&a[3] as *const u8, 1); // panic! out of bounds
    }
}