Press "Enter" to skip to content

Microsoft Previews Rust For Windows

Microsoft announced the preview of Rust for Windows, which aims to enable creating Rust apps for Windows using any Windows API.

Rust for Windows aims to make available both older and more recent APIs by leveraging the win32metadata project to create idiomatic projections of Windows API for languages other than C# and F#.

Rust for Windows is available through the windows crate:

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 windows crate is able to generate bindings to all required Windows API on the fly. You specify which types you require inside of a build.rs file:

fn main() {
    windows::build!(
        Windows::Data::Xml::Dom::*,
        Windows::Win32::WindowsProgramming::CloseHandle,
        Windows::Win32::WindowsAndMessaging::MessageBoxA,
        Windows::Win32::SystemServices::{
            CreateEventW, SetEvent, WaitForSingleObject
        },
    );
}

The generated bindings can be then imported and used in Rust source files:

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

use bindings::{
    Windows::Data::Xml::Dom::*,
    Windows::Win32::SystemServices::{CreateEventW, SetEvent, WaitForSingleObject, PWSTR},
    Windows::Win32::WindowsAndMessaging::{MessageBoxA, HWND, MESSAGEBOX_STYLE},
    Windows::Win32::WindowsProgramming::CloseHandle,
};

Microsoft has provided a number of sample programs exercising various Windows APIs, including Direct2DMicrosoft.Web.WebView2.CoreWin2D, and others. Additionally, Robert Mikhayelyan has ported Minesweeper to Windows for Rust.

Rust is the latest language projection derived from win32metadata. Not only does win32metadata enable automated Windows API projections, it also strives to make using them easier by converting non-specific types like uint into specific enums, opaque types like HANDLE and GDI objects into strongly-typed structs, and so on.

Rust documentation for all projected APIs is also available to describe how the Windows APIs and types are projected into idiomatic Rust.

As mentioned, Rust for Windows is still in preview and the project welcomes contributions to identify and fix bugs in the source code.