CsWin32 COM Interop Guide
Struct-based COM interop using CsWin32 patterns — AOT-compatible, no [ComImport] or built-in marshalling.
Paired skill: cswin32-interop covers general P/Invoke and the blittable signature rules that apply to both [DllImport] and COM vtables. This file covers only the COM-specific layer.
Workflow
- Interface in Win32 metadata? Add the name to
src/Framework/NativeMethods.txt→ CsWin32 generates it. Not in metadata (WMI, Fusion, Setup Configuration) → define a manual struct under its own folder, excluded from source builds via<Compile Remove>. - Lifetime:
using ComScope<T> scope = new();for every transient COM pointer (CoCreateInstance,QueryInterface,IEnumXxx::Next, factory output, app-localSTDAPI Get*, etc.). Never writeT* local; try { ... } finally { local->Release(); }— that's the pre-ComScopeshape that leaks on every early return. Same forBSTRout-params:using BSTR x = default;. - Activate via
ComClassFactory.TryCreate(CLSID, ...)(AOT-compatible) orPInvoke.CoCreateInstancewithIID.Get<T>()— not&localGuid. - Call via
scope.Pointer->Method(...). PassComScope<T>directly where the API expectsT**/void**— the implicit operator does the address-of. - Match the caller's error contract. If the top-level consumer swallows COM failure ("no result" == "absent"), helpers return
default/falseinstead of throwing aCOMExceptionthat's immediately discarded.ThrowOnFailureonly when the exception will actually propagate or assert a should-never-happen. - Guard with
#if FEATURE_WINDOWSINTEROP— add&& NETonly when the struct uses the static-abstractIComIIDform exclusively (no net472 dual-target).
Manual COM Structs (Not in Metadata)
Define each interface in its own file under e.g. src/Tasks/AssemblyDependency/Fusion/, src/Framework/Shared/VisualStudio/, src/Framework/Utilities/Wmi/. Exclude from source builds. Pattern (dual-target — works on net472 + .NET):
internal unsafe struct IAssemblyCache : IComIID
{
public static readonly Guid IID_IAssemblyCache = new(0xE707DCDE, ...);
#if NET
static ref readonly Guid IComIID.Guid
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref Unsafe.AsRef(in IID_IAssemblyCache);
}
#else
readonly ref readonly Guid IComIID.Guid
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref Unsafe.AsRef(in IID_IAssemblyCache);
}
#endif
private readonly void** _lpVtbl;
// IUnknown at indices 0-2, then interface methods at 3+
public HRESULT QueryInterface(Guid* riid, void** ppvObject)
{
fixed (IAssemblyCache* pThis = &this)
return ((delegate* unmanaged[Stdcall]<IAssemblyCache*, Guid*, void**, HRESULT>)_lpVtbl[0])(pThis, riid, ppvObject);
}
// AddRef @1, Release @2, then interface methods at correct slot indices.
}
Rules:
delegate* unmanaged[Stdcall]for the function-pointer cast — IDLSTDMETHODCALLTYPE⇒__stdcallon Win32. Picking the wrong convention silently corrupts the stack.IComIIDhas two shapes: static-abstract (static ref readonly Guid IComIID.Guid) on .NET 7+, instance (readonly ref readonly Guid IComIID.Guid) on net472 / netstandard2.0. CsWin32 picks the right one for its generated structs automatically (see IComIID across TFMs); a manual struct must spell out both arms itself. For .NET-only structs (WMI), drop the#elsebranch and gate the whole file#if NET. For dual-target structs (Fusion), keep both as shown — seesrc/Tasks/AssemblyDependency/Fusion/for the canonical example.- Use CsWin32-generated
PCWSTR/PWSTRfor wide strings (add toNativeMethods.txt); rawchar*only when no typed equivalent exists. - Vtable slots are exact: index 0 =
QueryInterface, 1 =AddRef, 2 =Release, 3+ = interface methods in IDL order. When inheriting, add the parent interface's method count before counting your own (e.g.ISetupConfiguration2.EnumAllInstancesis at slot 6 = 3 IUnknown + 3 v1 + 0). - CS0592 prevents
[SupportedOSPlatform]on structs — put it on individual methods.
Lifetime & Access
A raw T* (COM struct) is forbidden as a field on a non-ref type. Allowed locations: locals in unsafe methods, parameters, fields of a ref struct. Anywhere else (instance fields of class / non-ref struct) → use AgileComPointer<T> — a raw pointer field is an apartment-agility hazard and leaks on finalize-without-Dispose.
`ComScope<T>` — transient pointers
ref struct, using'd, calls Release on dispose. The default for everything that doesn't survive the current method. Implicitly converts to T** and void**, so out-params write into the scope directly:
using ComScope<ISomeInterface> scope = new();
Guid clsid = SomeStruct.CLSID;
Guid iid = IID.Get<ISomeInterface>();
PInvoke.CoCreateInstance(&clsid, null, CLSCTX.CLSCTX_INPROC_SERVER, &iid, scope).ThrowOnFailure();
scope.Pointer->DoThing(...);
using ComScope<IOther> other = new();
Guid otherIid = IOther.IID_IOther;
scope.Pointer->QueryInterface(&otherIid, other).ThrowOnFailure();
- Access methods via
scope.Pointer->Method(...). Null-check withscope.IsNull. - Applies to every COM out-param:
CoCreateInstance,QueryInterface,IEnumXxx::Next, factory methods, app-localSTDAPI Get*(declare the[DllImport]withT** pp, notout T*, so the implicit operator binds).
Ownership transfer out of a helper. A helper that acquires a COM pointer can return ComScope<T> directly; intermediate pointers stay in their own using scopes and Release on the helper's return. default ComScope<T> is null and its Dispose is a no-op, so callers don't need an extra null guard:
private static ComScope<ISetupConfiguration2> AcquireSetupConfig()
{
Guid clsid = SetupConfiguration.CLSID_SetupConfiguration;
Guid iid = ISetupConfiguration2.IID_ISetupConfiguration2;
ComScope<ISetupConfiguration2> config = new();
HRESULT hr = PInvoke.CoCreateInstance(&clsid, null, CLSCTX.CLSCTX_INPROC_SERVER, &iid, config);
if (hr.Succeeded) return config; // ownership flows to caller
if (hr != HRESULT.REGDB_E_CLASSNOTREG) return default;
using ComScope<ISetupConfiguration> v1 = new(); // intermediate, Released on return
if (SetupConfiguration.GetSetupConfiguration(v1, IntPtr.Zero) < 0 || v1.IsNull) return default;
return v1.Pointer->QueryInterface(&iid, config).Succeeded ? config : default;
}
// caller:
using ComScope<ISetupConfiguration2> config = AcquireSetupConfig();
if (!config.IsNull) { /* use config.Pointer */ }