Skip to content

Commit

Permalink
Merge pull request #28 from jewlexx/cominit-refactoring
Browse files Browse the repository at this point in the history
COM_INIT refactoring
  • Loading branch information
jewlexx committed Sep 8, 2023
2 parents 3845890 + cf0deca commit 89a115c
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions src/win/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,34 @@ use std::sync::Mutex;

use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED};

pub(crate) static COM_INIT: Mutex<ComInit> = Mutex::new(ComInit { initialized: false });

#[cfg(feature = "network")]
pub mod network;
#[cfg(feature = "root")]
pub mod root;

pub(crate) static COM_INIT: Mutex<ComInit> = Mutex::new(ComInit { initialized: false });

#[derive(Debug, Clone)]
pub(crate) struct ComInit {
initialized: bool,
}

impl ComInit {
pub(crate) fn init() {
let is_init = unsafe { Self::init_com() }.is_ok();
COM_INIT.lock().unwrap().initialized = is_init;
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ComError {
#[error("Failed to lock COM_INIT variable: {0}")]
LockError(#[from] std::sync::PoisonError<std::sync::MutexGuard<'static, ComInit>>),
}

unsafe fn init_com() -> Result<(), windows::core::Error> {
let mut com_init = COM_INIT.lock().unwrap();
impl ComInit {
pub(crate) unsafe fn init() {
let mut com_init = COM_INIT.lock().expect("unpoisoned mutex");
if !com_init.initialized {
CoInitializeEx(None, COINIT_MULTITHREADED)?;
com_init.initialized = true;
com_init.initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
}

Ok(())
}
}

// As COM_INIT is a static variable this will be dropped at the end of the program.
impl Drop for ComInit {
fn drop(&mut self) {
unsafe { CoUninitialize() }
Expand Down

0 comments on commit 89a115c

Please sign in to comment.