gpt4 book ai didi

winapi - 使用 Windows API 在 Rust 中打开文件

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

let mut file = OpenFile(dll_path.as_bytes_with_nul().as_ptr() as _, &mut ofstruct, 0) as *mut c_void;
let mut buffer_read: LPVOID = std::ptr::null_mut();

ReadFile(file, buffer_read, 5, std::ptr::null_mut(), std::ptr::null_mut());

println!("{:?}", buffer_read.is_null());

我无法为 buffer_read 找到正确的类型,它始终为 null。

最佳答案

只是因为您可以 链接到 Windows C file API在 Rust 中,并不意味着你应该这样做。特别是,这会剥夺您语言本身赋予的一大堆安全保障以及您所犯的错误。

特别是,您的代码当前有 UB,因为将 NULL 同时传递给 ReadFile 的最后两个参数是明确警告不要出现的情况:

lpNumberOfBytesRead

A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

This parameter can be NULL only when the lpOverlapped parameter is not NULL.

在您的情况下,安全地执行此操作的惯用方法如下:

let mut buffer_read = vec![0, 5];
let fhandle = std::fs::File::open("path/to/your/file")?;
fhandle.read_exact(&mut buffer_read)?;
println!("{}", String::from_utf8(buffer_read));

关于winapi - 使用 Windows API 在 Rust 中打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58333397/

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