Skip to content

joverwey/windows-rs

 
 

Repository files navigation

crates.io docs.rs Build and Test

Rust for Windows

The windows crate lets you call any Windows API past, present, and future using code generated on the fly directly from the metadata describing the API and right into your Rust package where you can call them as if they were just another Rust module.

The Rust language projection follows in the tradition established by C++/WinRT of building language projections for Windows using standard languages and compilers, providing a natural and idiomatic way for Rust developers to call Windows APIs.

Getting started

Start by adding the following to your Cargo.toml file:

[dependencies]
windows = "0.2.1"

[build-dependencies]
windows = "0.2.1"

This will allow Cargo to download, build, and cache Windows support as a package. Next, specify which types you need inside of a build.rs build script and the windows crate will generate the necessary bindings:

fn main() {
    windows::build!(
        windows::data::xml::dom::*
        windows::win32::system_services::{CreateEventW, SetEvent, WaitForSingleObject}
        windows::win32::windows_programming::CloseHandle
    );
}

Finally, make use of any Windows APIs as needed.

mod bindings {
    ::windows::include_bindings!();
}

use bindings::{
    windows::data::xml::dom::*,
    windows::win32::system_services::{CreateEventW, SetEvent, WaitForSingleObject},
    windows::win32::windows_programming::CloseHandle,
};

fn main() -> windows::Result<()> {
    let doc = XmlDocument::new()?;
    doc.load_xml("<html>hello world</html>")?;

    let root = doc.document_element()?;
    assert!(root.node_name()? == "html");
    assert!(root.inner_text()? == "hello world");

    unsafe {
        let event = CreateEventW(
            std::ptr::null_mut(),
            true.into(),
            false.into(),
            std::ptr::null(),
        );

        SetEvent(event).ok()?;
        WaitForSingleObject(event, 0);
        CloseHandle(event).ok()?;
    }

    Ok(())
}

To reduce build time, use a bindings crate rather simply a module. This will allow Cargo to cache the results and build your project far more quickly.

There is an experimental documentation generator for the Windows API. The documentation is published here. This can be useful to figure out how the various Windows APIs map to Rust modules and which use paths you need to use from within the build macro.

For a more complete example, take a look at Robert Mikhayelyan's Minesweeper. More simple examples can be found here.

About

Rust for Windows

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Rust 100.0%