简单的 Pop 然后加载回来不起作用
调用返回对象的函数后,我尝试将堆栈上的值存储在局部变量中,然后将其推回原处,但失败并出现异常
调用目标已引发异常
代码如下:
.....
MethodInfo checked_static = typeof(NameSpace1.Class1).GetMethod(
"Check", new Type[1] { typeof(object) });
adderIL.Emit(OpCodes.Callvirt, checked_static);
adderIL.Emit(OpCodes.Stloc_3);
adderIL.Emit(OpCodes.Ldloc_3);
adderIL.Emit(OpCodes.Brfalse, TRUE);
.....
如果我删除 Stloc_3
和 Ldloc_3
一切正常,我会迷失在这里。
After calling a function, which returns an object
, I try to store the value on stack in a local variable and then push it back, but it fails with an exception
Exception has been thrown with a target of invocation
Code is as follows:
.....
MethodInfo checked_static = typeof(NameSpace1.Class1).GetMethod(
"Check", new Type[1] { typeof(object) });
adderIL.Emit(OpCodes.Callvirt, checked_static);
adderIL.Emit(OpCodes.Stloc_3);
adderIL.Emit(OpCodes.Ldloc_3);
adderIL.Emit(OpCodes.Brfalse, TRUE);
.....
If I remove Stloc_3
and Ldloc_3
everything works fine, I am lost here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您对我的问题的答复,您似乎尚未声明您的本地。 IL 中的每个方法都指示它使用的所有局部变量的类型,因此您需要在
adderIL
实例上使用DeclareLocal
重载之一来声明它。如果您还没有声明任何其他本地变量,那么您还需要使用OpCodes.Stloc_0
而不是OpCodes.Stloc_3
(对于加载也是如此);或者,您可以只使用OpCodes.Stloc
或OpCodes.Stloc_S
并从DeclareLocal
调用中传递LocalBuilder
实例,如下所示adderIL.Emit 的第二个参数(在这种情况下,Reflection.Emit 库将为您从本地获取正确的索引)。Based on your response to my question, it appears that you haven't declared your local. Each method in IL indicates the types of all of the locals that it uses, so you need to declare it using one of the
DeclareLocal
overloads on youradderIL
instance. If you haven't declared any other locals, then you'll also need to useOpCodes.Stloc_0
instead ofOpCodes.Stloc_3
(and likewise for the loads); alternatively you can just useOpCodes.Stloc
orOpCodes.Stloc_S
and pass theLocalBuilder
instance from theDeclareLocal
call as the second argument toadderIL.Emit
(in which case the Reflection.Emit library will get the correct index from the local for you).