How to insert CIL code to C#

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

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

5条回答
  •  佛祖请我去吃肉
    2021-02-01 18:29

    I just posted a utility which allows entire C# function bodies to be automatically replaced with inline IL, using a custom attribute. Like similar utilities, this works via the ILDASM/ILASM round-trip which can be set up as a post-build step. The tool also adjusts the PDB in order to preserve single-stepping and setting breakpoints on individual IL instructions in the debugger. It's different from some of the other round-trip IL inliners in that it (only) substitutes for entire function bodies, like this:

        class MyClass
        {
            [ILFunc(@"
        .locals init ([0] int32 i_arg)
            ldc.i4.3
            ret
        ")]
            int MyFunc(int i_arg)
            {
                return 3;
            }
        };
    

    For highly performance-critical methods, I tried using DynamicMethod to improve upon compiler-generated IL, but found that the benefit is lost due to the delegate-calling overhead. Inline IL gives the the beneft of hand-tuned IL without that hit, assuming there are no runtime customizations that you would truly need DynamicMethod for.

    The complete source code is located at http://www.glennslayden.com/code/c-sharp/inline-il

提交回复
热议问题