将类方法转换为IL并在运行时执行它

时间:2016-12-09 17:15:56

标签: c# reflection cil methodinfo

我想将一个方法转换为一个类的IL代码,然后通过调用它来执行它。我关注的例子来自msdn:https://msdn.microsoft.com/en-us/library/system.reflection.emit.methodbuilder.createmethodbody(v=vs.110).aspx

它确切地显示了我需要的东西,我的问题是从类方法生成ILcodes。

所以基本上我需要填写以下内容

byte[] ILcodes = new byte[] {
      0x02,   /* 02h is the opcode for ldarg.0 */
  0x03,   /* 03h is the opcode for ldarg.1 */
  0x58,   /* 58h is the opcode for add     */
  0x2A    /* 2Ah is the opcode for ret     */
};

来自类中定义的方法,例如:

public class MethodBodyDemo
{ 
    public int Add(int x, int y)
    {
        return x + y;
    }
}

我尝试了以下调用来填充字节数组:

var ILcodes = typeof(MethodBodyDemo).GetMethod("Add").GetMethodBody().GetILAsByteArray();

以下是我正在创建的示例,但它提供了一个例外: “Common Language Runtime检测到无效程序。”

 public class MethodBodyDemo
{ 
    public int Add(int x, int y)
    {
        return x + y;
    }

    // This class will demonstrate how to create a method body using 
    // the MethodBuilder.CreateMethodBody(byte[], int) method.

    public static Type BuildDynType()
    {

        Type addType = null;

        AppDomain currentDom = Thread.GetDomain();

        AssemblyName myAsmName = new AssemblyName();
        myAsmName.Name = "MyDynamicAssembly";

        AssemblyBuilder myAsmBldr = currentDom.DefineDynamicAssembly(
                           myAsmName,
                           AssemblyBuilderAccess.RunAndSave);

        // The dynamic assembly space has been created.  Next, create a module
        // within it.  The type Point will be reflected into this module.

        ModuleBuilder myModuleBldr = myAsmBldr.DefineDynamicModule("MyModule");

        TypeBuilder myTypeBldr = myModuleBldr.DefineType("Adder");

        MethodBuilder myMthdBldr = myTypeBldr.DefineMethod("Add",
                                MethodAttributes.Public |
                                MethodAttributes.Static,
                                typeof(int),
                                new Type[]
                                {typeof(int), typeof(int)});
        // Build the array of Bytes holding the MSIL instructions.

     //   byte[] ILcodes = new byte[] {
     //         0x02,   /* 02h is the opcode for ldarg.0 */
        //  0x03,   /* 03h is the opcode for ldarg.1 */
        //  0x58,   /* 58h is the opcode for add     */
        //  0x2A    /* 2Ah is the opcode for ret     */
        //};

        var ILcodes = typeof(MethodBodyDemo).GetMethod("Add").GetMethodBody().GetILAsByteArray();

        myMthdBldr.CreateMethodBody(ILcodes, ILcodes.Length);

        addType = myTypeBldr.CreateType();

        return addType;
    }

    public static void TestExecMethod()
    {

        Type myType = BuildDynType();
        Console.WriteLine("---");
        Console.Write("Enter the first integer to add: ");
        int aVal = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter the second integer to add: ");
        int bVal = Convert.ToInt32(Console.ReadLine());

        object adderInst = Activator.CreateInstance(myType, new object[0]);

        Console.WriteLine("The value of adding {0} to {1} is: {2}.",
                   aVal, bVal,
                        myType.InvokeMember("Add",
                                 BindingFlags.InvokeMethod,
                                 null,
                                 adderInst,
                                 new object[] { aVal, bVal }));
    }

}

通过调用执行:

MethodBodyDemo.TestExecMethod();

请帮忙吗?

2 个答案:

答案 0 :(得分:3)

我是一个做同样事情的图书馆的作者。它读取现有方法的操作码,将它们重新解释为包含ieInfoInfo而不是编号令牌的通用操作码项,并从中构建方法副本。这可以进行交叉组装,也适用于您的情况。

它被设计为猴子补丁游戏,但可以修改为将“明文”中的通用操作码传输到不同的系统,以便目标可以进行类型查找,从而获得本地程序集的正确操作码。

该项目获得MIT许可,名为Harmony

答案 1 :(得分:2)

Release模式构建项目,并执行以下操作之一:

在此处删除MethodAttributes.Static属性

MethodBuilder myMthdBldr = myTypeBldr.DefineMethod("Add",
                           MethodAttributes.Public |
                           MethodAttributes.Static,
                           typeof(int),
                           new Type[]
                           {typeof(int), typeof(int)});

或者将此方法更改为static

public int Add(int x, int y)
{
    return x + y;
}

这应该适合你。

enter image description here

但是,我在评论中看到你希望它将字节传递给其他系统并运行它,我的回答仅仅是你在问题中的例子。实际上,由于西蒙·斯文森(Simon Svensson)在评论中写道的原因,这种方式无法奏效。 (除非所有方法都是静态的并且执行纯操作(如返回3 + 4)而不引用其他方法\ types \ fields。)

你仍然可以(理论上)做一些魔术让它发挥作用,但实际上并不是这样。