'Getting a windows-rs HWND from winit?
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.
Solution 1:[1]
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
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ian S. |