gpt4 book ai didi

rust - 如何获得下一个指针?

转载 作者:行者123 更新时间:2023-11-29 08:27:19 24 4
gpt4 key购买 nike

我有一个用 C 实现的函数,我想用 Rust 编写一个具有相同接口(interface)的函数。该函数接收指向数组开头的指针 (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
}

最佳答案

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

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

下面是一些使用 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
}
}

关于rust - 如何获得下一个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com