当前位置:   article > 正文

Rust 调用 Windows API_rust winapi

rust winapi

winapi 依赖包

Cargo.toml 文件内容如下:

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

示例程序:

  1. #[cfg(windows)]
  2. extern crate winapi;
  3. use std::io::Error;
  4. #[cfg(windows)]
  5. fn print_message(msg: &str) -> Result<i32, Error> {
  6. use std::ffi::OsStr;
  7. use std::iter::once;
  8. use std::os::windows::ffi::OsStrExt;
  9. use std::ptr::null_mut;
  10. use winapi::um::winuser::{MessageBoxW, MB_OK};
  11. let wide: Vec<u16> = OsStr::new(msg).encode_wide().chain(once(0)).collect();
  12. let ret = unsafe { MessageBoxW(null_mut(), wide.as_ptr(), wide.as_ptr(), MB_OK) };
  13. if ret == 0 {
  14. Err(Error::last_os_error())
  15. } else {
  16. Ok(ret)
  17. }
  18. }
  19. #[cfg(not(windows))]
  20. fn print_message(msg: &str) -> Result<(), Error> {
  21. println!("{}", msg);
  22. Ok(())
  23. }
  24. fn main() {
  25. print_message("Hello, world!你好!").unwrap();
  26. }

运行一下,结果如下:

非常 OK! 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/609502
推荐阅读
相关标签
  

闽ICP备14008679号