Skip to content

Bug: InvalidCastException because failed to create a CCW in AOT for IAsyncOperation<> #2378

@zhuxb711

Description

@zhuxb711

Description

An WinRT API described below:

public static class MyClass
{
    public static IAsyncOperation<IReadOnlyList<MyData>> TestAsync ()
    {
        return AsyncInfo.Run((CancelToken) => new ReadOnlyCollection<MyData>([new MyData()]));
    }
}

Everything OK if AOT not enabled. However, once AOT enabled. The caller will get an InvalidCastException. Failed to create a CCW for ReadOnlyCollection<MyData>.

After adding the code below, it works again in AOT.

[assembly: GeneratedWinRTExposedExternalType(typeof(ReadOnlyCollection<MyData>))]

I want to know will this exception be fixed in CsWinRT 2.3 and adding GeneratedWinRTExposedExternalType for the generic collection is just a temporary workaround? Or it's not a bug and we should always use GeneratedWinRTExposedExternalType to every generic collection variant to make it works in AOT?

What is the difference for my case after #1877 collection expression implemented in CsWinRT 2.3 ?

public static IAsyncOperation<IReadOnlyList<MyData>> TestAsync ()
{
    // After CsWinRT 2.3, this will also works?
    // Will we still need GeneratedWinRTExposedExternalType(typeof(ReadOnlyCollection<MyData>)) ?
    return AsyncInfo.Run((CancelToken) => [new MyData()]);
    // return AsyncInfo.Run((CancelToken) => new ReadOnlyCollection<MyData>([new MyData()]));
}

Steps To Reproduce

See code above

Expected Behavior

Should generate the CCW automatically for anything like

IAsyncOperation<IReadOnlyList<>>
IAsyncOperation<IList<>>
IAsyncOperation<IEnumerable<>>
IAsyncOperation<ICollection<>>

Version Info

Microsoft.Windows.CsWinRT 2.2.0

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions