0

我有一个用 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
}
4

1 回答 1

2

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

大多数时候,您使用指针,您的函数将是不安全的(因为您通常需要在某些时候取消引用它)。将它们标记为不安全以将安全责任委托给调用者可能是一个好主意。

以下是一些使用offsetand的示例from_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
    }
}
于 2017-05-02T06:59:13.327 回答