microsoft / windows-rs

Rust for Windows
https://kennykerr.ca/rust-getting-started/
Apache License 2.0
10.1k stars 473 forks source link

Implement static COM objects #3144

Open sivadeilra opened 3 days ago

sivadeilra commented 3 days ago

This allows you to define "static COM objects". Static COM objects are COM objects that are stored in static fields. This avoids the need for a separate heap allocation for stateless COM objects. It also allows const fn initialization of static COM objects.

A static COM object is not the same as a ComObject<T> stored in a static field. ComObject<T> is a pointer, which owns 1 reference count, to an allocated COM object. StaticComObject<T> directly contains the COM object's data, its reference count, and its vtable pointers.

Just like ComObject<T>, StaticComObject<T> allows you to cast it to any interface chain or interface pointer, and even to create a ComObject<T> that points to the StaticComObject<T>. This is safe because creating the ComObject<T> increases the reference count of the static object; dropping the ComObject<T> decreases the reference count, but it will never reach zero so it will never be "freed" (which would be wrong).

This feature is intended to support and simplify apps that need to define factory objects and other stateless objects. There is no need to heap-allocate these objects. This also simplifies their initialization because we simply never need to run any initialization logic at all, so we eliminate "order of initialization" bugs.