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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::marker::PhantomData;
use std::rc::Rc;
const RPC_E_CHANGED_MODE: u32 = 0x8001_0106;
/// Keeps COM initialized on the current thread for the lifetime of the guard.
/// Successful initializations are balanced; an existing different apartment
/// remains owned by its caller.
pub(crate) struct ComApartment {
owns_init: bool,
_thread_affinity: PhantomData<Rc<()>>,
}
impl ComApartment {
/// Join the MTA, or reuse an existing apartment with a different model.
pub(crate) fn enter() -> Result<Self, String> {
use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
// SAFETY: a successful call is balanced by Drop on this thread.
let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
let owns_init = if hr.is_ok() {
true
} else if hr.0 as u32 == RPC_E_CHANGED_MODE {
false
} else {
return Err(format!(
"CoInitializeEx(COINIT_MULTITHREADED) failed: 0x{:08X}",
hr.0 as u32
));
};
Ok(Self {
owns_init,
_thread_affinity: PhantomData,
})
}
}
impl Drop for ComApartment {
fn drop(&mut self) {
if self.owns_init {
// SAFETY: balances the successful call in enter on the same thread.
unsafe { windows::Win32::System::Com::CoUninitialize() };
}
}
}