Problems with generation of dynamic code
Posted
by user308344
on Stack Overflow
See other posts from Stack Overflow
or by user308344
Published on 2010-05-15T18:05:02Z
Indexed on
2010/05/15
18:44 UTC
Read the original article
Hit count: 390
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");
}
© Stack Overflow or respective owner