use std::marker::PhantomData;
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
#[derive(Debug)]
pub struct ComGuard {
_not_send: PhantomData<*mut ()>,
}
impl ComGuard {
pub fn new() -> anyhow::Result<Self> {
let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
if let Err(e) = hr.ok() {
tracing::error!(error = ?e, "COM MTA initialization failed");
return Err(anyhow::anyhow!("CoInitializeEx failed: {e}"));
}
tracing::debug!("COM MTA initialized");
Ok(Self {
_not_send: PhantomData,
})
}
}
impl Drop for ComGuard {
fn drop(&mut self) {
tracing::debug!("COM MTA teardown");
unsafe {
CoUninitialize();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn com_guard_constructs_and_drops() {
let guard = ComGuard::new();
assert!(guard.is_ok(), "ComGuard::new() should succeed: {guard:?}");
}
}