mercredi 29 juin 2016

Add objects to list in loop in IL Emit - Common Language Runtime detected an invalid program

The following is my C# code:

List<int> list = new List<int>();
for(int Count = 0; Count < 5; Count++)
    list.Add(Count);
return list;

My corresponding emitted code is as follows:



LocalBuilder list = ILout.DeclareLocal(typeof(List<int>));
            LocalBuilder Count = ILout.DeclareLocal(typeof(int));
            LocalBuilder CmpRes = ILout.DeclareLocal(typeof(bool));
            ConstructorInfo DictConstrctor = typeof(List<int>).GetConstructor(new Type[] { });
            MethodInfo methodinfo_add = typeof(List<int>).GetMethod("Add", new[] { typeof(int) });
            Label IL_001C = ILout.DefineLabel();
            Label IL_000B = ILout.DefineLabel();

            ILout.Emit(OpCodes.Newobj, DictConstrctor);
            ILout.Emit(OpCodes.Stloc_0, list);
            ILout.Emit(OpCodes.Ldc_I4_0);
            ILout.Emit(OpCodes.Stloc_1, Count);

            ILout.Emit(OpCodes.Br_S, IL_001C);
            ILout.MarkLabel(IL_000B);
            ILout.Emit(OpCodes.Ldloc_0, list);
            ILout.Emit(OpCodes.Ldloc_1, Count);
            ILout.Emit(OpCodes.Call, methodinfo_add);

            ILout.Emit(OpCodes.Ldloc_1, Count);
            ILout.Emit(OpCodes.Ldc_I4_1);
            ILout.Emit(OpCodes.Add);

            ILout.Emit(OpCodes.Stloc_1, Count);
            ILout.MarkLabel(IL_001C);
            ILout.Emit(OpCodes.Ldloc_1, Count);
            ILout.Emit(OpCodes.Ldc_I4_2);
            ILout.Emit(OpCodes.Clt);
            ILout.Emit(OpCodes.Stloc_3, CmpRes);
            ILout.Emit(OpCodes.Ldloc_3, CmpRes);
            ILout.Emit(OpCodes.Brtrue_S, IL_000B);

            ILout.Emit(OpCodes.Ldloc_0, list);
            ILout.Emit(OpCodes.Ret);

It is throwing an exception - "Common Language Runtime detected an invalid program.".

What is it that I am doing wrong here? Any help is appreciated.





Aucun commentaire:

Enregistrer un commentaire