Debian Codegraph @

.cargo/vendor/windows-core/src/com_interface.rs

raw
1 use super::*;
2
3 /// Provides low-level access to a COM interface.
4 ///
5 /// This trait is automatically implemented by the generated bindings and should not be
6 /// implemented manually.
7 ///
8 /// # Safety
9 ///
10 /// It is only safe to implement this trait if the implementing type is a valid COM interface pointer meaning
11 /// the following criteria are met:
12 /// * its in-memory representation is equal to `NonNull<NonNull<Self::VTable>>`
13 /// * the vtable is correctly structured beginning with the `IUnknown` function pointers
14 /// * the vtable must be the correct vtable for the supplied IID
15 pub unsafe trait ComInterface: Interface + Clone {
16 /// A unique identifier representing this interface.
17 const IID: GUID;
18
19 // Casts the `ComInterface` to a `IUnknown`.
20 fn as_unknown(&self) -> &IUnknown {
21 // SAFETY: it is always safe to treat a `ComInterface` as an `IUnknown`.
22 unsafe { std::mem::transmute(self) }
23 }
24
25 /// Attempts to cast the current interface to another interface using `QueryInterface`.
26 ///
27 /// The name `cast` is preferred to `query` because there is a WinRT method named query but not one
28 /// named cast.
29 fn cast<T: ComInterface>(&self) -> Result<T> {
30 let mut result = None;
31 // SAFETY: `result` is valid for writing an interface pointer and it is safe
32 // to cast the `result` pointer as `T` on success because we are using the `IID` tied
33 // to `T` which the implementor of `ComInterface` has guaranteed is correct
34 unsafe { self.query(&T::IID, &mut result as *mut _ as _).and_some(result) }
35 }
36
37 /// Attempts to create a [`Weak`] reference to this object.
38 fn downgrade(&self) -> Result<Weak<Self>> {
39 self.cast::<crate::imp::IWeakReferenceSource>().and_then(|source| Weak::downgrade(&source))
40 }
41
42 /// Call `QueryInterface` on this interface
43 ///
44 /// # Safety
45 ///
46 /// `interface` must be a non-null, valid pointer for writing an interface pointer.
47 unsafe fn query(&self, iid: *const GUID, interface: *mut *mut std::ffi::c_void) -> HRESULT {
48 (self.assume_vtable::<IUnknown>().QueryInterface)(self.as_raw(), iid, interface)
49 }
50 }