microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.
MIT License
1.99k stars 84 forks source link

How to create instance for `IDesktopWallpaper` COM interface #1168

Closed seayxu closed 2 months ago

seayxu commented 2 months ago

Is your feature request related to a problem? Please describe.

[Guid("B92B56A9-8B55-4E14-9A89-0199BBB6F93B"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown),ComImport()]
[SupportedOSPlatform("windows8.0")]
[global::System.CodeDom.Compiler.GeneratedCode("Microsoft.Windows.CsWin32", "0.3.49-beta+91f5c15987")]
internal interface IDesktopWallpaper
{
}

The code not gen GeneratedComInterface,so not gen implement in below.

[GeneratedComClass]
internal partial class DesktopWallpaper : IDesktopWallpaper
{
}
AArnott commented 2 months ago

The [GeneratedComClass] attribute is unrelated to this source generator. CsWin32 generates all the code necessary for interop of the APIs it emits, as far as I'm aware. I'm not too familiar with that attribute but from the docs you linked to (thank you!) it seems that that triggers a source generator to fill in more. But as a source generator itself, CsWin32 cannot depend on the compiler running any other source generator after itself, so it must be self-sufficient.

Further, I see that both IDesktopWallpaper and DesktopWallpaper are in the metadata, so I expect both can be emitted by CsWin32.

Can you clarify what it generates and how that falls short to support your scenario?

dongle-the-gadget commented 2 months ago

CsWin32 currently uses the built-in COM interop system via [ComImport] (when runtime marshalling is enabled), which isn't trimming or AOT compatible. [GeneratedComClass] and [GeneratedComInterface] are two attributes introduced in .NET 8 to support the new source-generated COM wrappers, which are trimming and AOT compatible.

As far as I'm aware, when an attribute is marked with [GeneratedComInterface], a source generator then provides the [IUnknownDerivedAttribute<T,TImpl>] (source code) attribute for it, which provides metadata for the StrategyBasedComWrappers class to initiate RCWs and CCWs for the interface.

AArnott commented 2 months ago

when runtime marshalling is enabled

I think you've already qualified your statement appropriately here. If you don't want to rely on the built-in COM interop system, turn off allowMarshaling in the NativeMethods.json file. This is what WinForms does in order to get trim-friendly COM interop from CsWin32.