Search code examples
winui-3winuiwinui-xaml

Exception in ISwapChainPanelNative Only in Release Mode (WinUI 3, C#)


I am developing a WinUI 3 application in C#. I am using SwapChainPanel, but an exception occurs only in Release mode. Where is the switch mentioned in the error message? I referred to the URL, but I couldn't find it.

Error Message:

Built-in COM has been disabled via a feature switch. See https://aka.ms/dotnet-illink/com for more information.

Here is the code where the error occurs:

ISwapChainPanelNative panelNative = MySwapChainPanel.As<ISwapChainPanelNative>();

And here is the definition of ISwapChainPanelNative:

[Guid("63aad0b8-7c24-40ff-85a8-640d944cc325")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
internal interface ISwapChainPanelNative
{
    int SetSwapChain([In] IntPtr swapChain);
}

Solution

  • Build-in COM has been disabled for some reason in your project, maybe you use AOT or IL-trimming?

    So, you can't use the "old" way of declaring interface or functions with attributes such as ComImport or DllImport, which rely on code generation at run time.

    Instead, you want to use the new COM interop Source generator and define the interface like this instead, using the GeneratedComInterface attribute:

    [GeneratedComInterface, Guid("63aad0b8-7c24-40ff-85a8-640d944cc325")]
    public partial interface ISwapChainPanelNative
    {
        [PreserveSig]
        int SetSwapChain(IDXGISwapChain swapChain);
    }
    

    This will cause the source generator to build interop code at compile time.

    PS: all this is only valid in a .NET 8 and higher context.