当前位置: 代码迷 >> 综合 >> Rust 调用 Windows API
  详细解决方案

Rust 调用 Windows API

热度:92   发布时间:2023-12-12 15:28:04.0

winapi 依赖包

Cargo.toml 文件内容如下:

[package]
name = "winapi"
version = "0.1.0"
edition = "2018"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winuser"] }

示例程序:

#[cfg(windows)]
extern crate winapi;
use std::io::Error;#[cfg(windows)]
fn print_message(msg: &str) -> Result<i32, Error> {use std::ffi::OsStr;use std::iter::once;use std::os::windows::ffi::OsStrExt;use std::ptr::null_mut;use winapi::um::winuser::{MessageBoxW, MB_OK};let wide: Vec<u16> = OsStr::new(msg).encode_wide().chain(once(0)).collect();let ret = unsafe { MessageBoxW(null_mut(), wide.as_ptr(), wide.as_ptr(), MB_OK) };if ret == 0 {Err(Error::last_os_error())} else {Ok(ret)}
}
#[cfg(not(windows))]
fn print_message(msg: &str) -> Result<(), Error> {println!("{}", msg);Ok(())
}
fn main() {print_message("Hello, world!你好!").unwrap();
}

运行一下,结果如下:

非常 OK! 

 

  相关解决方案