【发布时间】:2017-01-25 19:49:33
【问题描述】:
在discussing/learning about the correct way to call a FFI of the Windows-API from Rust 之后,我玩得更远了,想再次检查一下我的理解。
我有一个被调用两次的 Windows API。在第一次调用中,它返回实际输出参数所需的缓冲区大小。然后,使用足够大小的缓冲区再次调用它。我目前正在使用 Vec 作为此缓冲区的数据类型(参见下面的示例)。
代码有效,但我想知道这是否是正确的方法,或者使用alloc::heap::allocate 之类的函数直接保留一些内存然后使用transmute 将结果从FFI 回来了。同样,我的代码有效,但我试图在幕后看一点。
extern crate advapi32;
extern crate winapi;
extern crate widestring;
use widestring::WideCString;
use std::io::Error as IOError;
use winapi::winnt;
fn main() {
let mut lp_buffer: Vec<winnt::WCHAR> = Vec::new();
let mut pcb_buffer: winapi::DWORD = 0;
let rtrn_bool = unsafe {
advapi32::GetUserNameW(lp_buffer.as_mut_ptr(),
&mut pcb_buffer )
};
if rtrn_bool == 0 {
match IOError::last_os_error().raw_os_error() {
Some(122) => {
// Resizing the buffers sizes so that the data fits in after 2nd
lp_buffer.resize(pcb_buffer as usize, 0 as winnt::WCHAR);
} // This error is to be expected
Some(e) => panic!("Unknown OS error {}", e),
None => panic!("That should not happen"),
}
}
let rtrn_bool2 = unsafe {
advapi32::GetUserNameW(lp_buffer.as_mut_ptr(),
&mut pcb_buffer )
};
if rtrn_bool2 == 0 {
match IOError::last_os_error().raw_os_error() {
Some(e) => panic!("Unknown OS error {}", e),
None => panic!("That should not happen"),
}
}
let widestr: WideCString = unsafe { WideCString::from_ptr_str(lp_buffer.as_ptr()) };
println!("The owner of the file is {:?}", widestr.to_string_lossy());
}
依赖关系:
[dependencies]
advapi32-sys = "0.2"
winapi = "0.2"
widestring = "*"
【问题讨论】: