1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use super::*;
use crate::{GUID, HRESULT, IUnknown, Interface};
use core::ffi::c_void;
/// A reference-counted, COM-compatible heap allocation used by generated WinRT delegate types.
///
/// The bindgen-generated `*<Delegate>::new()` allocates an instance of this type and reinterprets
/// the resulting pointer as the delegate. This type supplies the shared `QueryInterface`,
/// `AddRef`, and `Release` implementations; generated delegates provide only their `Invoke`
/// thunk.
#[repr(C)]
#[doc(hidden)]
pub struct DelegateBox<I: Interface, F> {
pub vtable: *const I::Vtable,
pub invoke: F,
pub count: RefCount,
}
impl<I: Interface, F> DelegateBox<I, F> {
/// Creates a new `DelegateBox` with a reference count of 1.
pub fn new(vtable: *const I::Vtable, invoke: F) -> Self {
#[cfg(windows_cast_diagnostics)]
live_objects::DELEGATES.add();
Self {
vtable,
invoke,
count: RefCount::new(1),
}
}
/// Generic `IUnknown::QueryInterface` implementation for delegate boxes.
///
/// Responds to the delegate's own IID, `IUnknown`, `IAgileObject`, and (on Windows) `IMarshal`.
pub unsafe extern "system" fn QueryInterface(
this: *mut c_void,
iid: *const GUID,
interface: *mut *mut c_void,
) -> HRESULT {
unsafe {
let this = this as *mut *mut c_void as *mut Self;
if iid.is_null() || interface.is_null() {
return HRESULT(-2147467261); // E_POINTER
}
*interface = if *iid == <I as Interface>::IID
|| *iid == <IUnknown as Interface>::IID
|| *iid == <IAgileObject as Interface>::IID
{
// Later calls and the final Release need the whole allocation's provenance.
this.cast()
} else {
#[cfg(windows)]
if *iid == <IMarshal as Interface>::IID {
(*this).count.add_ref();
return marshaler(IUnknown::from_raw(this.cast()), interface);
}
core::ptr::null_mut()
};
if (*interface).is_null() {
HRESULT(-2147467262) // E_NOINTERFACE
} else {
(*this).count.add_ref();
HRESULT(0)
}
}
}
/// Generic `IUnknown::AddRef` implementation for delegate boxes.
pub unsafe extern "system" fn AddRef(this: *mut c_void) -> u32 {
unsafe {
let this = this as *mut *mut c_void as *mut Self;
(*this).count.add_ref()
}
}
/// Generic `IUnknown::Release` implementation for delegate boxes.
pub unsafe extern "system" fn Release(this: *mut c_void) -> u32 {
unsafe {
let this = this as *mut *mut c_void as *mut Self;
let remaining = (*this).count.release();
if remaining == 0 {
let _ = Box::from_raw(this);
}
remaining
}
}
}
#[cfg(windows_cast_diagnostics)]
impl<I: Interface, F> Drop for DelegateBox<I, F> {
fn drop(&mut self) {
live_objects::DELEGATES.remove();
}
}