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環境。之後,可以按照以下步驟操作:
在你的計畫中添加
windows
依賴:
# Cargo.toml
[dependencies]
windows = "0.34.0"
在你的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 = [0u16; 512];
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() asu32) as *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 = [0u16; 512];
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
語
言
」
學
習
資
料