Expand description
§Introduction
This crate exposes a single public-facing function: current()
. It returns the load
address of the PE image containing the currently executing code. This address, when
reinterpreted as an HINSTANCE
or
HMODULE
, serves as
a module identifier used throughout the Win32 API to reference per-module resources,
code, and data.
This is useful in contexts such as:
- Loading embedded resources (icons, cursors, dialogs)
- Registering window classes
- Setting up global hooks
§Interoperability
Values returned by current()
are typically reinterpreted as HINSTANCE
or
HMODULE
handles to interface with Win32 APIs. Since popular Win32 bindings represent
these types differently, this section outlines how to integrate with the three most
common crates.
§windows-sys
This low-level binding crate uses type aliases for HINSTANCE
and HMODULE
:
pub type HINSTANCE = *mut c_void;
pub type HMODULE = *mut c_void;
These are identical to the return type of current()
and values can be passed
without conversion:
let cursor = unsafe { LoadCursorW(hmod::current(), w!("arrow")) };
§windows
The higher-level windows
crate wraps Win32 handles in newtypes for stronger type
safety. Its HINSTANCE
and HMODULE
types are defined as:
pub struct HINSTANCE(pub *mut c_void);
pub struct HMODULE(pub *mut c_void);
Since the fields are public, these wrappers can be constructed via direct initialization:
let hmod = hmod::current();
let hmod = HINSTANCE(hmod); // construct wrapper
let cursor = unsafe { LoadCursorW(Some(hmod), w!("arrow")) }?;
This crate does not implement From
traits for these types to avoid coupling to a
specific version of the windows
crate.
§winapi
The winapi
crate models HINSTANCE
as a pointer to an empty enum to prevent
accidental construction and enforce type safety at compile time. HMODULE
is a type
alias for HINSTANCE
:
pub enum HINSTANCE__ {}
pub type HINSTANCE = *mut HINSTANCE__;
pub type HMODULE = HINSTANCE;
To convert to winapi
-compatible types an as
-cast is required:
let hmod = hmod::current();
let hmod = hmod as HINSTANCE;
let cursor = unsafe { LoadCursorW(hmod, w!("arrow")) };
§Implementation details
This crate makes use of the __ImageBase
pseudo-variable (as explained in Raymond
Chen’s blog post Accessing the current module’s HINSTANCE from a static
library). It is a
synthetic symbol supplied by the linker, located at relative virtual address (RVA)
zero.
The __ImageBase
symbol is provided by all mainstream Windows linkers (MSVC’s
link.exe, Clang’s lld, and MinGW’s ld).
The value is resolved at module load time. Accessing it involves a single memory load at run-time, with no function calls or system interaction.
Functions§
- current
- Returns the load address of the PE image that contains the currently executing code. This address serves as a module handle in Win32 APIs.