windows-core 0.101.0

Core type support for COM and Windows
Documentation
use super::*;
use core::marker::PhantomData;

/// `Weak` holds a non-owning reference to an object.
///
/// This type is not [`Send`] or [`Sync`]. It does not marshal the native weak reference between
/// apartments. Cross-apartment use requires explicitly marshaling the native `IWeakReference`
/// interface, for example with [`AgileReference`].
/// The native weak interfaces are available through `windows-bindgen` or
/// `windows::Win32::System::WinRT::{IWeakReference, IWeakReferenceSource}`.
#[derive(Clone, PartialEq, Eq)]
pub struct Weak<I: Interface>(Option<imp::IWeakReference>, PhantomData<I>);

impl<I: Interface> Default for Weak<I> {
    fn default() -> Self {
        Self::new()
    }
}

impl<I: Interface> Weak<I> {
    /// Creates a new `Weak` object without any backing object.
    pub const fn new() -> Self {
        Self(None, PhantomData)
    }

    /// Attempts to upgrade the weak reference to a strong reference.
    pub fn upgrade(&self) -> Option<I> {
        self.0.as_ref().and_then(|inner| unsafe {
            let mut value = core::ptr::null_mut();
            // Resolve returns the interface selected by the IID, not necessarily IInspectable.
            (inner.vtable().Resolve)(inner.as_raw(), &I::IID, &mut value)
                .and_then(|| imp::from_abi(value))
                .ok()
        })
    }

    pub(crate) fn downgrade(source: &imp::IWeakReferenceSource) -> Self {
        let reference = unsafe { source.GetWeakReference().ok() };
        Self(reference, PhantomData)
    }
}