Cysharp / MemoryPack

Zero encoding extreme performance binary serializer for C# and Unity.
MIT License
3.37k stars 203 forks source link

NativeAOT compatibility: publish warnings and how to make MemoryPack fully NativeAOT compatible? #211

Closed xiaoyuvax closed 8 months ago

xiaoyuvax commented 10 months ago

when publish with NATIVEAOT, following warnings thrown, does it matter?

Assembly 'MemoryPack.Core' produced AOT analysis warnings. Assembly 'MemoryPack.Core' produced trim warnings. For more information see https://aka.ms/dotnet-illink/libraries

during runtime (seems built-in types were trimmed):

System.Collections.Generic.IDictionary2[[System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[MyType] is failed in provider at creating formatter. 'MemoryPack.Formatters.InterfaceDictionaryFormatter2[MyType]' is missing native code or metadata. This can happen for code that is not compatible with trimming or AOT. Inspect and fix trimming and AOT related warnings that were generated when the app was published. For more information see https://aka.ms/nativeaot-compatibility

Can MemoryPack be sured to be nativeaot compaitible?

hadashiA commented 8 months ago

Hello. Currently, MemoryPack uses reflection in part to resolve Formatter. Therefore, it is not able to fully pass the AOT check by the compiler.

However, Try the version after #237 is merged. For example, the following code you are concerned about worked with NativeAOT on my end.

var dict = new Dictionary<string, MyType>
{
    { "a", new MyType { X = 100 } }
};

var bin = MemoryPackSerializer.Serialize(dict);
var d = MemoryPackSerializer.Deserialize<IDictionary<string, MyType>>(bin)!;
System.Console.WriteLine(d["a"].X);

[MemoryPackable]
partial class MyType
{
    public int X { get; set; }
}

If you have specific problematic code, please let us know, and I welcome a reopen.