Problems with generation of dynamic code
- by user308344
This code gif an exception: Invocation exception, please help, I don't know what happen, I think is some thing with the Add because he work when I push onto the stack intergers, and when i push lvalue It's didn't work, thanks
static void Main(string[] args)
{
AppDomain dominioAplicacion = System.Threading.Thread.GetDomain();
AssemblyName nombre_Del_Ensamblado = new AssemblyName("ASS");
AssemblyBuilder ensambladoBld = dominioAplicacion.DefineDynamicAssembly(nombre_Del_Ensamblado, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder moduloBld = ensambladoBld.DefineDynamicModule("<MOD");
TypeBuilder claseContenedoraBld = moduloBld.DefineType("claseContenedora");
MethodBuilder mainBld = claseContenedoraBld.DefineMethod("main", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
ILGenerator il = mainBld.GetILGenerator();
FieldBuilder campoBld = claseContenedoraBld.DefineField("x", typeof(int), FieldAttributes.Public | FieldAttributes.Static);
il.Emit(OpCodes.Ldc_I4, 2);
il.Emit(OpCodes.Stsfld, campoBld);
FieldBuilder campoBld1 = claseContenedoraBld.DefineField("x1", typeof(int), FieldAttributes.Public | FieldAttributes.Static);
il.Emit(OpCodes.Ldc_I4, 2);
il.Emit(OpCodes.Stsfld, campoBld1);
il.Emit(OpCodes.Ldftn, campoBld);
//il.Emit(OpCodes.Unbox, typeof(int));
//il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldftn, campoBld1);
//il.Emit(OpCodes.Unbox, typeof(int));
il.Emit(OpCodes.Stloc_1);
il.Emit(OpCodes.Ldloc_1);
//il.Emit(OpCodes.Box, typeof(int));
//il.Emit(OpCodes.Ldftn, campoBld1);
//il.Emit(OpCodes.Unbox, typeof(int));
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Pop);
//il.Emit(OpCodes.Stsfld, campoBld1);
il.Emit(OpCodes.Ret);
Type t = claseContenedoraBld.CreateType();
object ptInstance = Activator.CreateInstance(t, new Type[] { });
t.InvokeMember("main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
null,
ptInstance,
new object[0]);
var x = t.GetField("x");
}