将原始C字符串读取到Rust。在这种情况下,将带符号转换为无符号的正确方法是什么?

问题描述 投票:1回答:1

我将某些C函数绑定到锈。我面临一个小问题,我想知道解决锈蚀的正确方法。

这是我想从C API调用的函数:

extern "C" {
    pub fn H5Aread(attr_id: hid_t, type_id: hid_t, buf: *mut c_char) -> herr_t;
}

该功能从文件中读取内容,并将其存储在buf中。

所以,我在向量中创建了此缓冲区:

let len: u64 = get_the_length();

let attr_raw_string: Vec<c_char> = Vec::new(); // c_char is equivalent to i8
attr_raw_string.resize(len as usize, 0);
let attr_raw_string_ptr = attr_raw_string.as_mut_ptr();

let read_error = H5Aread(attr_obj, attr_type, attr_raw_string_ptr);
if read_error < 0 {
    panic!("...");
}
let result_str: String = String::from_utf8(attr_raw_string);

现在,由于from_utf8需要Vec<u8>,但Vec<c_char>Vec<i8>,因此无法编译。

是否有解决此问题的方法,而不必每次都将字符串复制和转换为新类型u8

c string vector utf-8 rust
1个回答
0
投票

您可以使用mem::transmute重新解释基础存储块。在这种情况下,u8i8的大小相同是安全的。

let len: u64 = get_the_length();

let attr_raw_string = vec![0; len as usize];
let attr_raw_string_ptr = attr_raw_string.as_mut_ptr();

let read_error = H5Aread(attr_obj, attr_type, attr_raw_string_ptr);
if read_error < 0 {
    panic!("...");
}
let attr_raw_string = unsafe {
    std::mem::transmute::<Vec<i8>, Vec<u8>>(attr_raw_string)
};
let result_str: String = String::from_utf8(attr_raw_string);
© www.soinside.com 2019 - 2024. All rights reserved.