microsoft / windows-rs

Rust for Windows
https://kennykerr.ca/rust-getting-started/
Apache License 2.0
10.36k stars 486 forks source link

convert &IFooBar to ManuallyDrop<Option<IFooBar>> #3062

Closed nxcy closed 3 months ago

nxcy commented 4 months ago

Suggestion

https://github.com/microsoft/windows-rs/blob/dbc3932513ba9ed489c0b99c1bb3aba565d23994/crates/samples/windows/direct3d12/src/main.rs#L496 Is this documented? Is there a safer way to do the conversion?

nxcy commented 4 months ago

Can ManuallyDrop<Option<IFooBar>> be replaced with RawPointerToCom<IFooBar> ?

#[repr(transparent)]
pub struct RawPointerToCom<'a, T> {
    _a: std::mem::ManuallyDrop<Option<T>>,
    _b: std::marker::PhantomData<&'a T>,
}

impl<'a, T> RawPointerToCom<'a, T> {
    pub fn from_com_ref(r: &'a T) -> Self {
        unsafe { std::mem::transmute_copy(r) }
    }
}
sivadeilra commented 4 months ago

There is a new type in the windows_core crate, called InterfaceRef, which serves exactly this purpose now. It has not yet been published, but I expect that we'll publish a new version of all of the Windows crates within the next 2 weeks.

kennykerr commented 4 months ago

It's not quite the right solution as it expects a lifetime parameter which cannot easily be added to structs like D3D12_RESOURCE_BARRIER. We also need to figure out a better harmony between ParamValue, which doesn't have lifetime, and InterfaceRef, which does. And neither are a perfect fit for windows-bindgen to use for structs, which would be the requirement to satisfy this issue.