首页 新闻 会员 周边 捐助

Emit实现一个简单的Add操作,不知道哪里出了问题

0
悬赏园豆:5 [已关闭问题] 关闭于 2014-02-27 15:35

IL代码:

.method public hidebysig 
    instance int32 Add (
        int32 p1,
        int32 p2
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 9 (0x9)
    .maxstack 2
    .locals init (
        [0] int32 CS$1$0000
    )

    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: ldarg.2
    IL_0003: add
    IL_0004: stloc.0
    IL_0005: br.s IL_0007

    IL_0007: ldloc.0
    IL_0008: ret
}

C#代码:

        public delegate int Populator(int p1, int p2);

        public void EmitAdd()
        {
            var dynamicMethod = new DynamicMethod("DoAdd", typeof(int), new Type[] { typeof(int), typeof(int) });
            var il = dynamicMethod.GetILGenerator();
            var label = il.DefineLabel();
            var retlbl = il.DeclareLocal(typeof(int));

            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Add);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Br_S, label);
            il.MarkLabel(label);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);

            var act = (Populator)dynamicMethod.CreateDelegate(typeof(Populator));

            var r = act(1, 2);
        }

调用总是报:请求的操作对 DynamicMethod 无效。

JRoger的主页 JRoger | 菜鸟二级 | 园豆:258
提问于:2014-02-27 14:39
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册