I am creating my own program for changing .exe code via dnlib.
Then I want to create a Dictionary via IL and Dnlib code.
But there are not many tutorials for both so it's pretty hard..
It writes wrong Dictionary code and makes DnSpy crash.
My code:
MethodDef cctor = Module.GlobalType.FindOrCreateStaticConstructor();
IList<Instruction> inst = cctor.Body.Instructions;
var objectCtor = new MemberRefUser(Module, ".ctor",
MethodSig.CreateInstance(Module.CorLibTypes.Void),
Module.CorLibTypes.Object.TypeDefOrRef);
var Global_Array = new FieldDefUser(
"field_obfuscator_array",
new FieldSig(Module.CorLibTypes.GetCorLibTypeSig(,
FieldAttributes.Public | FieldAttributes.Static);
Module.GlobalType.Fields.Add(Global_Array);
if (inst.Count < 1)
inst.Add(new Instruction(OpCodes.Ret));
inst.Insert(0, new Instruction(OpCodes.Ldc_I4, 100000));
inst.Insert(1, new Instruction(OpCodes.Newobj, "[mscorlib]System.Collections.Generic.Dictionary`2"));
inst.Insert(2, new Instruction(OpCodes.Stsfld, Global_Array));
Any help is highly appreciated, thanks!
The easiest way is to write this implementation in C# then drop it in decompiler (eg dnspy in this case or other doesnt matter - just need to be have IL code reader).
There is 3-ways to do this:
C#->ILor click to open with right-click on mouse, here is!edit method body, done! After that you could just write the same IL code as well as in dnspy via dnlib.Importer(do your magic - import this method, a lot of examples is right here)Example code for dnlib how it could be done: