wincom 0.3.0

A lightweight Rust wrapper for Windows COM IDispatch automation, providing RAII VARIANT management and simplified property/method invocation.
Documentation
//! Property and method access on `IDispatch`.
//!
//! The entry point is [`ComObject`], which wraps an `IDispatch` pointer
//! and offers four kinds of operations:
//!
//! | Operation | Method |
//! |-----------|--------|
//! | Read a property | [`ComObject::get_property`] |
//! | Write a property | [`ComObject::set_property`] |
//! | Call a method | [`ComObject::invoke_method`] |
//! | Call with `[in,out]` params | [`ComObject::invoke_method_inout`] |
//!
//! # Argument order
//!
//! COM's `DISPPARAMS.rgvarg` stores arguments **in reverse order** relative
//! to the source-level call. `ComObject` accepts arguments in the natural
//! source order and reverses them internally, so callers do not need to
//! think about it:
//!
//! ```no_run
//! # use wincom::{ComObject, Variant};
//! # fn example(app: &ComObject) -> wincom::Result<()> {
//! // Calls `app.SomeMethod(a, b, c)` — not `SomeMethod(c, b, a)`.
//! app.invoke_method("SomeMethod", vec![
//!     Variant::from_i32(1),       // a
//!     Variant::from_str("x"),     // b
//!     Variant::from_bool(true),   // c
//! ])?;
//! # Ok(())
//! # }
//! ```
//!
//! # Type libraries
//!
//! `ComObject` uses `IDispatch::GetIDsOfNames` to resolve names to dispid
//! values at runtime. This requires the COM server to expose its
//! automation interface via a type library. Servers that implement
//! vtable-based dual interfaces work too, as long as they respond to
//! `GetIDsOfNames`.

use windows::core::{GUID, HSTRING, IUnknown, Interface, PCWSTR};
use windows::Win32::Globalization::GetSystemDefaultLCID;
use windows::Win32::System::Com::{
    self, CoCreateInstance, IDispatch, CLSCTX_LOCAL_SERVER, DISPATCH_FLAGS, DISPATCH_METHOD,
    DISPATCH_PROPERTYGET, DISPATCH_PROPERTYPUT, DISPPARAMS,
};
use windows::Win32::System::Ole::{self, DISPID_PROPERTYPUT};
use windows::Win32::System::Variant::VARIANT;

use crate::err::{Error, Result};
use crate::variant::Variant;

/// `MK_E_UNAVAILABLE` — HRESULT returned by `GetActiveObject` when no
/// running instance is registered in the Running Object Table.
const MK_E_UNAVAILABLE: windows::core::HRESULT =
    windows::core::HRESULT(0x800401E3u32 as i32);

/// Wrapper around an `IDispatch` pointer.
///
/// `ComObject` provides name-based access to automation servers. It is
/// created either by:
///
/// - [`ComObject::new_from_active`] — bind to a running instance
///   (`GetActiveObject`). Returns `MK_E_UNAVAILABLE` if the application
///   is not running.
/// - [`ComObject::new_from_name`] — create a new instance
///   (`CoCreateInstance`). May launch a new process.
/// - [`ComObject::from_dispatch`] — take ownership of an existing
///   `IDispatch` (no `AddRef`).
///
/// # Thread safety
///
/// `ComObject` is **not** `Send` or `Sync`. COM objects are bound to the
/// apartment in which they were created. To use one from a different
/// thread, marshal it explicitly with
/// `CoMarshalInterThreadInterfaceInStream`, or create a fresh object per
/// thread.
///
/// # Lifetime
///
/// `ComObject` holds one reference to the `IDispatch`. It is released
/// when the `ComObject` is dropped. Constructing from a raw `IDispatch`
/// (via [`Self::from_dispatch`]) does **not** call `AddRef`, so the
/// caller must transfer ownership.
pub struct ComObject {
    /// IID / CLSID recorded at construction time.
    ///
    /// - For [`Self::new_from_active`], this is the **CLSID** resolved
    ///   from the ProgID.
    /// - For [`Self::new_from_name`] and [`Self::from_dispatch`], this is
    ///   whatever the caller passed.
    iid: GUID,
    disp: IDispatch,
}

impl ComObject {
    // ---------- Constructors ----------

    /// Creates a new COM object instance from a ProgID
    /// (`CoCreateInstance` with `CLSCTX_LOCAL_SERVER`).
    ///
    /// If no instance is running this **starts a new process**; if one is
    /// already running, the behavior (reuse vs. second instance) depends
    /// on the server's registration.
    ///
    /// # Parameters
    ///
    /// - `id`: the ProgID, e.g. `"CorelDRAW.Application"`.
    /// - `iid`: recorded as the object's identity; currently not used
    ///   for interface negotiation. See the note below.
    ///
    /// # Note on `iid`
    ///
    /// The returned `ComObject` always exposes `IDispatch`; `iid` is
    /// stored for informational purposes only. If you need a
    /// specific interface, use [`Self::as_dispatch`] and cast manually.
    ///
    /// # Errors
    ///
    /// - `CO_E_CLASSSTRING` (`0x800401F3`) if the ProgID is not
    ///   registered.
    /// - The server's own HRESULT if creation fails.
    pub fn new_from_name(id: &str, iid: GUID) -> Result<Self> {
        unsafe {
            let rclsid = Com::CLSIDFromProgID(&HSTRING::from(id))?;
            let unk: IUnknown = CoCreateInstance(&rclsid, None, CLSCTX_LOCAL_SERVER)?;
            Ok(Self { iid, disp: unk.cast()? })
        }
    }

    /// Binds to a running COM server identified by a ProgID.
    ///
    /// Calls `CLSIDFromProgID` followed by `GetActiveObject`. The most
    /// common failure is `MK_E_UNAVAILABLE (0x800401E3)`, which means no
    /// running instance is registered in the ROT — i.e. the target
    /// application is not running:
    ///
    /// ```no_run
    /// # use wincom::{ComObject, Error};
    /// match ComObject::new_from_active("CorelDRAW.Application") {
    ///     Ok(app) => println!("got CorelDRAW: {:?}", app.iid()),
    ///     Err(Error::Windows(e)) if e.code().0 == 0x800401E3u32 as i32 => {
    ///         eprintln!("CorelDRAW is not running — start it first");
    ///     }
    ///     Err(e) => eprintln!("unexpected error: {e}"),
    /// }
    /// ```
    ///
    /// # Argument
    ///
    /// `id` is a **ProgID** such as `"AutoCAD.Application"`, not an
    /// executable path.
    pub fn new_from_active(id: &str) -> Result<Self> {
        unsafe {
            let rclsid = Com::CLSIDFromProgID(&HSTRING::from(id))?;
            let mut app: Option<IUnknown> = None;
            Ole::GetActiveObject(&rclsid, None, &mut app)?;
            let unk = app.ok_or_else(|| {
                Error::Windows(windows::core::Error::new(
                    MK_E_UNAVAILABLE,
                    "no active object for progid",
                ))
            })?;
            Ok(Self { iid: rclsid, disp: unk.cast()? })
        }
    }

    /// Alias for [`Self::new_from_active`].
    pub fn new_from_app(id: &str) -> Result<Self> {
        Self::new_from_active(id)
    }

    /// Alias for [`Self::new_from_active`].
    ///
    /// # Argument
    ///
    /// Despite the name, `id` is a **ProgID**, not a `.exe` path.
    pub fn new_from_path(id: &str) -> Result<Self> {
        Self::new_from_active(id)
    }

    /// Wraps an existing `IDispatch` without calling `AddRef`.
    ///
    /// The caller transfers ownership of `disp` to the returned
    /// `ComObject`. If you want to keep your own reference, clone `disp`
    /// first (`disp.clone()` performs an `AddRef`).
    pub fn from_dispatch(disp: IDispatch, iid: GUID) -> Self {
        Self { iid, disp }
    }

    // ---------- Metadata ----------

    /// Returns the GUID recorded at construction time.
    ///
    /// See the [`ComObject`] struct documentation for what this value
    /// means for each constructor.
    pub fn iid(&self) -> GUID {
        self.iid
    }

    /// Borrows the underlying `IDispatch`.
    pub fn as_dispatch(&self) -> &IDispatch {
        &self.disp
    }

    /// Wraps the underlying `IDispatch` in a [`Variant`] (`AddRef`'d).
    ///
    /// The reference is released when the returned `Variant` is dropped.
    pub fn as_variant(&self) -> Variant {
        Variant::from_dispatch(&self.disp)
    }

    // ---------- Property / method calls ----------

    /// Reads a property with no arguments.
    ///
    /// Equivalent to `self.get_property_with(prop, Vec::new())`.
    pub fn get_property(&self, prop: &str) -> Result<Variant> {
        self.get_property_with(prop, Vec::new())
    }

    /// Reads a property with arguments (`DISPATCH_PROPERTYGET`).
    ///
    /// `args` are given in **source order**; they are reversed internally
    /// to match COM's `rgvarg` convention.
    ///
    /// # Errors
    ///
    /// - `DISP_E_UNKNOWNNAME` if `prop` is not exposed by the server.
    /// - The server's HRESULT if the getter itself fails.
    pub fn get_property_with(&self, prop: &str, mut args: Vec<Variant>) -> Result<Variant> {
        let dispid = self.get_id_from_name(prop)?;
        args.reverse();
        let mut dp = DISPPARAMS {
            cArgs: args.len() as u32,
            rgvarg: if args.is_empty() {
                std::ptr::null_mut()
            } else {
                args.as_mut_ptr() as *mut VARIANT
            },
            ..Default::default()
        };
        self.invoke_raw(dispid, DISPATCH_PROPERTYGET, &mut dp)
    }

    /// Writes a property (`DISPATCH_PROPERTYPUT`).
    ///
    /// `args` are given in **source order**. For a property taking a
    /// single value, `args` has exactly one element:
    ///
    /// ```no_run
    /// # use wincom::{ComObject, Variant};
    /// # fn example(app: &ComObject) -> wincom::Result<()> {
    /// app.set_property("Visible", vec![Variant::from_bool(true)])?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Same as [`Self::get_property`].
    pub fn set_property(&self, prop: &str, mut args: Vec<Variant>) -> Result<()> {
        let dispid = self.get_id_from_name(prop)?;
        args.reverse();
        let mut named = [DISPID_PROPERTYPUT];
        let mut dp = DISPPARAMS {
            cArgs: args.len() as u32,
            rgvarg: if args.is_empty() {
                std::ptr::null_mut()
            } else {
                args.as_mut_ptr() as *mut VARIANT
            },
            cNamedArgs: 1,
            rgdispidNamedArgs: named.as_mut_ptr(),
        };
        self.invoke_raw(dispid, DISPATCH_PROPERTYPUT, &mut dp)?;
        Ok(())
    }

    /// Calls a method with the given arguments (`DISPATCH_METHOD`).
    ///
    /// `args` are given in **source order**; they are reversed internally
    /// to match COM's `rgvarg` convention.
    ///
    /// # Errors
    ///
    /// - `DISP_E_UNKNOWNNAME` if `method` is not exposed.
    /// - The server's HRESULT if the call itself fails.
    pub fn invoke_method(&self, method: &str, mut args: Vec<Variant>) -> Result<Variant> {
        let dispid = self.get_id_from_name(method)?;
        args.reverse();
        let mut dp = DISPPARAMS {
            cArgs: args.len() as u32,
            rgvarg: if args.is_empty() {
                std::ptr::null_mut()
            } else {
                args.as_mut_ptr() as *mut VARIANT
            },
            ..Default::default()
        };
        self.invoke_raw(dispid, DISPATCH_METHOD, &mut dp)
    }

    /// Calls a method with `[in, out]` parameters.
    ///
    /// Each element of `args` is passed as `VT_BYREF | VT_VARIANT`.
    /// After the call returns, `args` contains the values written back by
    /// the server:
    ///
    /// ```no_run
    /// # use wincom::{ComObject, Variant};
    /// # fn example(app: &ComObject) -> wincom::Result<()> {
    /// // Suppose the server exposes `GetRange([in,out] long lo, [in,out] long hi)`.
    /// let mut args = vec![Variant::from_i32(0), Variant::from_i32(0)];
    /// app.invoke_method_inout("GetRange", &mut args)?;
    /// let lo = args[0].to_i32()?;
    /// let hi = args[1].to_i32()?;
    /// # let _ = (lo, hi);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Safety
    ///
    /// The `VT_BYREF` wrappers created inside this method hold raw
    /// pointers to elements of `args`. Those pointers are valid only
    /// during the call; the COM server must not retain them. The wrappers
    /// are dropped before returning, so `args` remains sound regardless.
    pub fn invoke_method_inout(
        &self,
        method: &str,
        args: &mut [Variant],
    ) -> Result<Variant> {
        let dispid = self.get_id_from_name(method)?;

        let mut byrefs: Vec<Variant> =
            args.iter_mut().map(Variant::byref_of).collect();
        byrefs.reverse();

        let mut dp = DISPPARAMS {
            cArgs: byrefs.len() as u32,
            rgvarg: if byrefs.is_empty() {
                std::ptr::null_mut()
            } else {
                byrefs.as_mut_ptr() as *mut VARIANT
            },
            ..Default::default()
        };

        let result = self.invoke_raw(dispid, DISPATCH_METHOD, &mut dp);
        // `byrefs` drops here. Their `VariantClear` only clears the
        // VT_BYREF wrapper itself, never the pointed-to target.
        drop(byrefs);
        result
    }

    // ---------- Internals ----------

    /// Resolves a property/method name to a dispid.
    fn get_id_from_name(&self, name: &str) -> Result<i32> {
        unsafe {
            let lcid = GetSystemDefaultLCID();
            let hstring = HSTRING::from(name);
            let names = [PCWSTR::from_raw(hstring.as_ptr())];
            let mut dispid: i32 = 0;
            self.disp
                .GetIDsOfNames(&GUID::zeroed(), names.as_ptr(), 1, lcid, &mut dispid)?;
            Ok(dispid)
        }
    }

    fn invoke_raw(
        &self,
        dispid: i32,
        flags: DISPATCH_FLAGS,
        dp: &mut DISPPARAMS,
    ) -> Result<Variant> {
        let mut result = Variant::empty();
        unsafe {
            // Convert &mut VARIANT to *mut VARIANT explicitly — the two
            // types are not interchangeable in `Option<...>`.
            let pvarresult: *mut VARIANT = result.as_raw_mut();
            self.disp.Invoke(
                dispid,
                &GUID::zeroed(),
                0,
                flags,
                dp,
                Some(pvarresult),
                None,
                None,
            )?;
        }
        Ok(result)
    }
}