gpt4 book ai didi

c# - 在 IL 生成中将局部变量加载到堆栈以进行方法调用?

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:20 25 4
gpt4 key购买 nike

我正在尝试生成 IL 以模仿以下方法 MyMethod:

public void DoSomething(object a, object b, string c, string d){...};
public virtual void MyMethod(object a, object b)
{
DoSomething(a, b, "hello", this.SomeInstanceString);
}

这是我目前所知道的,但我无法理解将第 3 个和第 4 个参数加载到堆栈以调用 DoSomething(a, b, "hello", this. SomeInstanceString)):

 MethodBuilder myMethod = typeBuilder.DefineMethod("MyMethod",
MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new[]
{ typeof(object), typeof(object) });
ILGenerator myMethodILGen = mbFromCustomObject.GetILGenerator();
myMethodILGen.Emit(OpCodes.Ldarg_0);
myMethodILGen.Emit(OpCodes.Ldarg_1);
// How do I load the string "hello" and the local instance
// variable this.SomeInstanceString onto the stack?
myMethodILGen.Emit(OpCodes.Call, GetMethodInfoForDoSomething());
myMethodILGen.Emit(OpCodes.Ret);

那么,如何将字符串"hello" 和局部实例变量this.SomeInstanceString 加载到堆栈上以调用DoSomething

最佳答案

加载字符串文字相当容易。

myMethodILGen.Emit(OpCodes.Ldstr, "hello");

从对象实例中加载字段要求您首先将对象实例加载到堆栈上,然后使用 Ldfld 操作码。您应该已经为您的 SomeInstanceString 字段准备了一个 FieldBuilder,您可以将其用于此目的。

FieldBuilder fieldBuilder = typeBuilder.DefineField(
"SomeInstanceString",
typeof(string),
FieldAttributes.Public);

myMethodILGen.Emit(OpCodes.Ldarg_0);
myMethodILGen.Emit(OpCodes.Ldfld, fieldBuilder);

另外,请记住,Ldarg_0 并不像您认为的那样。实例方法有一个隐式参数,它位于零槽中,其中包含该方法当前在其​​中运行的实例。这就是我们使用 Ldarg_0 取消引用该字段的原因,因为您可能需要该方法所在的实例。但这不适用于静态方法。

关于c# - 在 IL 生成中将局部变量加载到堆栈以进行方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com