How to insert CIL code to C#

前端 未结 5 2044
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 17:55

Is it possible to insert IL code to C# method?

5条回答
  •  旧巷少年郎
    2021-02-01 18:34

    I'll add my own tool to the list of solutions already provided here: InlineIL.Fody.

    This uses the Fody assembly weaving tool to modify the assembly at build time. Which means all you have to do is install a NuGet package, add a config file to your project and you're done.

    You're then provided with a simple and type-safe API to emit IL instructions, which you can mix with C# code. I believe it's easier to write IL in this way than writing text, and it's also more convenient than ILGenerator since each opcode gets its own method with relevant overloads only.

    Here's an example, with using static InlineIL.IL.Emit;:

    public static void ZeroInit(ref T value)
        where T : struct
    {
        Ldarg(nameof(value));
        Ldc_I4_0();
        Sizeof(typeof(T));
        Unaligned(1);
        Initblk();
    }
    

    This shows how to access the initblk instruction which C# doesn't currently expose.

提交回复
热议问题