当前位置: 欣欣网 > 码农

使用windows-rs在Rust中调用Windows API

2024-06-11码农

windows-rs 是一个由微软提供的开源项目,目标是让Rust开发者能够方便地调用Windows API。这些Windows API可以是过去的、现在的或未来的, windows-rs 可以直接从描述API的元数据中生成代码,使开发者能够将其作为普通的Rust模块来调用。

项目结构

该仓库包含多个crate(Rust的包管理单元),每个crate有其特定用途:

  • riddle : Windows元数据编译工具。

  • windows-bindgen : Windows元数据编译库。

  • windows-core : windows crate的类型支持。

  • windows-implement : windows crate的实现宏,用于实现COM接口。

  • windows-interface : windows crate的接口宏,用于声明COM接口。

  • windows-metadata : Windows元数据读取。

  • windows-registry : Windows注册表管理。

  • windows-result : Windows错误处理。

  • windows-sys : C风格的Windows API的原始绑定。

  • windows-targets : Windows的导入库。

  • windows-version : Windows版本信息。

  • windows : 包含了C风格的API以及COM和WinRT API的更安全的绑定。

  • 入门指南

    要使用 windows-rs ,首先需要安装Rust,确保你已经设置好了Rust环境。之后,可以按照以下步骤操作:

    1. 在你的项目中添加 windows 依赖:

    # Cargo.toml
    [dependencies]
    windows = "0.34.0"

    1. 在你的Rust代码中,你可以如下方式调用Windows API:

    use windows::{
    core::Result,
    Win32::System::Diagnostics::Debug::{self, FormatMessageW, GetLastError, FORMAT_MESSAGE_FROM_SYSTEM},
    Win32::Foundation::HWND,
    Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_OK},
    };
    fnmain() -> Result<()> {
    unsafe {
    MessageBoxW(HWND(0), "Hello, world!""Hello", MB_OK);
    }
    Ok(())
    }

    函数调用示例

    调用用户界面功能

    我们可以用 windows 来调用Windows的用户界面功能,比如MessageBox:

    use windows::{
    core::Result,
    Win32::Foundation::HWND,
    Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_OK},
    };
    fnmain() -> Result<()> {
    unsafe {
    MessageBoxW(HWND(0), "Hello, world!""Hello", MB_OK);
    }
    Ok(())
    }

    这个例子展示了如何使用 MessageBoxW 函数来显示一个消息框。

    读取注册表

    使用 windows-rs 我们还可以读取Windows注册表:

    use windows::{
    Win32::System::Registry::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_SZ},
    core::PWSTR,
    };
    fnmain() -> windows::core::Result<()> {
    letmut buffer = [0u16512];
    unsafe {
    RegGetValueW(
    HKEY_CURRENT_USER,
    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer",
    "Logon User Name",
    RRF_RT_REG_SZ,
    std::ptr::null_mut(),
    buffer.as_mut_ptr() as *mut _,
    &mut (buffer.len() asu32as *mut _,
    )?;
    let user_name = PWSTR(buffer.as_ptr()).to_string();
    println!("Current user: {}", user_name);
    }
    Ok(())
    }

    错误处理

    Windows API总是有可能返回错误。我们可以通过 GetLastError 函数来获取最后一次错误:

    use windows::{
    core::Result,
    Win32::System::Diagnostics::Debug::{GetLastError, FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM},
    };
    fnmain() -> Result<()> {
    // 模拟一个失败的API调用
    let error_code = unsafe { GetLastError() };
    if error_code != 0 {
    letmut buffer = [0u16512];
    unsafe {
    FormatMessageW(
    FORMAT_MESSAGE_FROM_SYSTEM,
    std::ptr::null(),
    error_code,
    0,
    buffer.as_mut_ptr(),
    buffer.len() asu32,
    std::ptr::null(),
    );
    }
    let message = String::from_utf16_lossy(&buffer);
    println!("Error: {}", message);
    }
    Ok(())
    }

    结论

    通过使用 windows-rs ,Rust开发者可以方便地调用Windows API。这不仅使得Rust在Windows平台上的开发变得更加容易,而且还允许开发者利用Rust的强类型系统和安全性来编写更可靠的代码。

    文章精选

    「Rust