Getting a windows-rs HWND from winit?

1.7k views Asked by At

I'm fairly new to Rust and am trying to get the following to work:

 let hwnd : *mut HWND = window.hwnd().cast();
 let swapchain = unsafe { factory.CreateSwapChainForHwnd(&device, *hwnd, &desc, std::ptr::null(), &output)? } ;

where window.hwnd() returns a *mut c_void and I need to cast that to a windows::Windows::Win32::Foundation::HWND , but this example crashes on a access violation. I assume its because I deref a pointer to a HWND whereas the HWND itself should be the void ptr. HWND can be created from an isize, so like HWND(isize) but I'm not sure if that should get the address of the void pointer or something? Any help is appreciated.

1

There are 1 answers

0
Ian S. On BEST ANSWER

You're right that you need to convert the pointer to an isize, so although this clashes with recent developments regarding pointer provenance, I believe the correct way to construct an HWND is as follows:

let hwnd = HWND(window.hwnd() as isize);

isize and usize are defined to be pointer width, so converting a raw pointer to one of these types is zero cost and essentially just erases type information.

Note this works because HWND is just a newtype struct whose single field is a pub isize, so the HWND(val) syntax just initializes the struct with that field set to val. To access that field you can just do my_hwnd.0, and convert to a pointer via my_hwnd.0 as *mut T.