简体   繁体   English

反射发出堆栈和方法调用

[英]Reflection emit stack and method call

Can someone explain to me what needs to be loaded into the stack prior to making a function call via reflection.emit? 有人可以向我解释在通过reflection.emit进行函数调用之前需要加载到堆栈中的内容吗?

I have a very simple method 我有一个非常简单的方法

public static void Execute(string 1, string 2)

I want to generate the method in the following class dynamically (forget the rest, I got them sorted out) 我想动态生成下面的类中的方法(忘记其余的,我把它们整理出来)

public class Test{
    public string s1;

    public void Run(string s2)
    {
        MyOtherClass.Execute(s2,s1)
    }
}

I have a copy of the above test, for reference, and I noticed the following opcodes were emitted, prior to the "call". 我有上述测试的副本供参考,我注意到在“调用”之前发出了以下操作码。

  1. ldarg_1 ldarg_1
  2. ldarg_0 ldarg_0
  3. ldfld ldfld

The question is what's ldarg_0 doing there? 问题是ldarg_0在那里做什么? I only need 2 arguments for the call, why does the CLR requires ldarg_0 to be pushed to the stack? 我只需要2个参数用于调用,为什么CLR需要将ldarg_0推送到堆栈?

arg.0 contains this and is required by ldfld string Test:s1 to push this.s1 onto the stack. arg.0包含this并且是ldfld string Test:s1this.s1推送到堆栈上所this.s1的。

.method public hidebysig instance void Run(string s2) cil managed
{
    .maxstack 8                                      // maximum stack size 8
    ldarg.1                                          // push argument s2
    ldarg.0                                          // push this
    ldfld string Test::s1                            // pop this, push this.s1
    call void MyOtherClass::Execute(string, string)  // call
    ret                                              // return
}

You need to push the method's arguments in order of declaration and an object reference if the method is not static. 如果方法不是静态的,您需要按声明的顺序推送方法的参数和对象引用。 In your test case, you are accessing a member field ( s1 ), so you need the this reference for it. 在您的测试用例中,您正在访问成员字段( s1 ),因此您需要this参考。 That's what ldarg_0 provides. 这就是ldarg_0提供的。 The subsequent ldfld pops the this reference and pushes the field's value onto the evaluation stack. 随后的ldfld弹出this引用并将字段的值推送到评估堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM