mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
// 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() };
        }
    }
}