Alignment about repr(C)

I'm reading win32 api source and printing size of the structs with WIndows 11 64bits rustc.

Following struct shows 72 with mem::size_of

#[repr(C)]
pub struct WNDCLASSA {
    pub style: WNDCLASS_STYLES, //32
    pub lpfnWndProc: WNDPROC,  //64
    pub cbClsExtra: i32,
    pub cbWndExtra: i32,
    pub hInstance: super::super::Foundation::HINSTANCE,//64
    pub hIcon: HICON,//64
    pub hCursor: HCURSOR,//64
    pub hbrBackground: super::super::Graphics::Gdi::HBRUSH,//64
    pub lpszMenuName: super::super::Foundation::PSTR,//64
    pub lpszClassName: super::super::Foundation::PSTR,
}

I cannot understand the alignment about it. Is there any easy way to show structs' memory alignment and element positions?

You can use the offset_of! macro like this:

fn main() {
    println!("style: {}", offset_of!(WNDCLASSA, style));
    println!("lpfnWndProc: {}", offset_of!(WNDCLASSA, lpfnWndProc));
}

This will print the offset of each field.

The macro is available in two places:

  • From the standard library, but it is unstable, so you need the nightly compiler.
  • From the bytemuck crate.
2 Likes

Thanks for your patience! It works well