microsoft / CsWinRT

C# language projection for the Windows Runtime
MIT License
540 stars 102 forks source link

AoT: Failing to cast object to byte[] #1796

Open dotMorten opened 6 hours ago

dotMorten commented 6 hours ago

Describe the bug

To Reproduce

  1. Create a new WinUI 3 app, and enable it for AoT
  2. Replace the MainWindow.xaml.cs code with the following:

        public MainWindow()
        {
            var settings = GetLocalSettings();
            if (!settings.Values.ContainsKey("Test"))
                settings.Values.Add("Test", new byte[] { 1, 2, 3, 4 });
            this.InitializeComponent();
        }
    
        private void myButton_Click(object sender, RoutedEventArgs e)
        {
            var settings = GetLocalSettings();
            var data = (byte[])settings.Values["Test"](); // BOOM! Unable to cast object of type 'WinRT.IInspectable' to type 'System.Byte[]'.
        }
    
        private ApplicationDataContainer GetLocalSettings()
        {
            var localSettings = ApplicationData.Current.LocalSettings;
            if (localSettings.Containers.TryGetValue("Settings", out var container))
                return container;
            return localSettings.CreateContainer("Settings", ApplicationDataCreateDisposition.Always);
        }
  3. Run the app and click the button.
  4. Observe the application crash: Unable to cast object of type 'WinRT.IInspectable' to type 'System.Byte[]'.

Expected behavior App settings gets the byte[].

Version Info WinAppSDK 1.6.0, CSWinRT 2.1.3

Additional context Also tried:

dongle-the-gadget commented 6 hours ago

I was under the impression that arrays are illegal to use outside of parameters in the WinRT type system.

https://learn.microsoft.com/en-us/uwp/winrt-cref/winrt-type-system#array-parameters

dotMorten commented 5 hours ago

@dongle-the-gadget are you saying we can't store any binary data (like data encrypted with the DataProtectionProvider) in the application settings? I mean it works fine - it's only in AoT mode it doesn't. .NET Native with UWP works fine also.

dongle-the-gadget commented 5 hours ago

It works but seems like undocumented behavior. The supported list of types in docs also doesn’t mention arrays. I suppose though that you can probably cast the object into an IPropertyValue and get the array from there.

dongle-the-gadget commented 5 hours ago

By any chance did you disable IReference support?

dotMorten commented 5 hours ago

By any chance did you disable IReference support?

Not that I know off? The code is in a net8.0-windows library. No explicit reference to WindowsAppSDK.