Skip to main content

implement

Attribute Macro implement 

#[implement]
Expand description

Implements one or more COM interfaces for a struct or enum.

use windows_core::*;

#[interface("094d70d6-5202-44b8-abb8-43860da5aca2")]
unsafe trait IValue: IUnknown {
    fn GetValue(&self, value: *mut i32) -> HRESULT;
}

#[implement(IValue)]
struct Value(i32);

impl IValue_Impl for Value_Impl {
    unsafe fn GetValue(&self, value: *mut i32) -> HRESULT {
        unsafe { *value = self.0 };
        HRESULT(0)
    }
}

let _: IValue = Value(123).into();

Implementations must be 'static + Send + Sync: interfaces can outlive their creator, COM calls may overlap, and another thread may release the final reference. Agile = false does not enforce thread affinity in the MTA.

A Send field that is not Sync cannot be published, even with agility disabled:

ⓘ
use std::cell::Cell;
use windows_core::*;

#[interface("094d70d6-5202-44b8-abb8-43860da5aca2")]
unsafe trait IValue: IUnknown {}

#[implement(IValue, Agile = false)]
struct Value(Cell<u32>);

impl IValue_Impl for Value_Impl {}

let _: IValue = Value(Cell::new(0)).into();

A Sync field that is not Send is also rejected, including for static storage:

ⓘ
use std::sync::MutexGuard;
use windows_core::*;

#[interface("094d70d6-5202-44b8-abb8-43860da5aca2")]
unsafe trait IValue: IUnknown {}

#[implement(IValue)]
struct Value(Option<MutexGuard<'static, ()>>);

impl IValue_Impl for Value_Impl {}

let _ = Value(None).into_static();

Interfaces can outlive their creator, so implementations cannot borrow stack data:

ⓘ
use windows_core::*;
#[interface("094d70d6-5202-44b8-abb8-43860da5aca2")]
unsafe trait IValue: IUnknown {}
#[implement(IValue, Agile = false)]
struct Value<'a>(&'a u32);
impl IValue_Impl for Value_Impl<'_> {}
fn escape() -> IValue {
    let value = 123;
    Value(&value).into()
}

Constructing a ComObject does not permit borrowed implementation state either:

ⓘ
use windows_core::*;
#[implement(Agile = false)]
struct Value<'a>(&'a u32);
fn escape() -> IUnknown {
    let value = 123;
    ComObject::new(Value(&value)).into_interface()
}

Requesting only a borrowed interface view still requires 'static implementation state:

ⓘ
use windows_core::*;
#[implement(Agile = false)]
struct Value<'a>(&'a u32);
fn escape() -> IUnknown {
    let value = 123;
    let object = ComObject::new(Value(&value));
    object.as_interface::<IUnknown>().to_owned()
}

Lifetime-generic types can still refer to static data:

use windows_core::*;
#[implement]
struct Value<'a>(&'a u32);
static VALUE: u32 = 123;
let object = ComObject::new(Value(&VALUE));
assert_eq!(*object.get().0, 123);
let interface: IUnknown = object.clone().into_interface();
assert_eq!(interface, object.as_interface::<IUnknown>().to_owned());