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.
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
DeclareLocaloverloads on youradderILinstance. If you haven’t declared any other locals, then you’ll also need to useOpCodes.Stloc_0instead ofOpCodes.Stloc_3(and likewise for the loads); alternatively you can just useOpCodes.StlocorOpCodes.Stloc_Sand pass theLocalBuilderinstance from theDeclareLocalcall as the second argument toadderIL.Emit(in which case the Reflection.Emit library will get the correct index from the local for you).