我将某些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
?
您可以使用mem::transmute
重新解释基础存储块。在这种情况下,u8
和i8
的大小相同是安全的。
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);