Cysharp / MemoryPack

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

Is static constructor possible in class annotated with [MemoryPackable] #167

Closed Donis- closed 11 months ago

Donis- commented 1 year ago

Great work, thank you. We see impressive performance.

Is there a way to allow static constructor in the original partial class that is annotated with [MemoryPackable]? Or a way to execute user code from the MemoryPack generated static constructor. At the moment MemoryPack seems to generate a static constructor in it's partial part of the class unconditionally:

https://github.com/Cysharp/MemoryPack/blob/9aa51ce1e8da24e27053bf2448c127c4263c2096/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs#L942C1-L947C6

And then compiler complains about duplicate static constructor if the original partial class has it too.

Maybe it's possible to allow the user to call the registration directly from the original partial class static constructor

global::MemoryPack.MemoryPackFormatterProvider.Register<{TypeName}>();
Jonathan-Gardner commented 1 year ago

I've also ran into this issue.

If it's preferred for MemoryPack to ensure Register is called; could a static partial method be added to the generator?

partial struct MyStruct : IMemoryPackable<MyStruct>
{
    static partial void StaticConstructor();

    static MyStruct()
    {
        global::MemoryPack.MemoryPackFormatterProvider.Register<MyStruct>();
        StaticConstructor();
    }

    ...

As long as it returns void it would be optional for users to implement it and removed by the compile if it's not. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods#partial-methods

Jonathan-Gardner commented 1 year ago

Made a quick PR https://github.com/Cysharp/MemoryPack/pull/187

neuecc commented 1 year ago

I see, there is indeed a problem with static constructors. The PR looks good, I will look at it later.

lloyd-perfectstorm commented 12 months ago

I've run into this too. It would be great to have a way to either disable the generators static constructor, so I can write my own and call RegisterFormatter myself or a way do annotate an additional static method to call would be great.

neuecc commented 11 months ago

merged and released in v1.10.0.