How to use Mono.Cecil to create HelloWorld.exe

How do you use Mono.Cecil to create a simple program from scratch? All the examples and manuals that I have been able to find so far suggest that you are working with an existing assembly, reading or making small changes.

+6
source share
2 answers

To get started, see the following code:

var myHelloWorldApp = AssemblyDefinition.CreateAssembly( new AssemblyNameDefinition("HelloWorld", new Version(1, 0, 0, 0)), "HelloWorld", ModuleKind.Console); var module = myHelloWorldApp.MainModule; // create the program type and add it to the module var programType = new TypeDefinition("HelloWorld", "Program", Mono.Cecil.TypeAttributes.Class | Mono.Cecil.TypeAttributes.Public, module.TypeSystem.Object); module.Types.Add(programType); // add an empty constructor var ctor = new MethodDefinition(".ctor", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName | Mono.Cecil.MethodAttributes.RTSpecialName, module.TypeSystem.Void); // create the constructor method body var il = ctor.Body.GetILProcessor(); il.Append(il.Create(OpCodes.Ldarg_0)); // call the base constructor il.Append(il.Create(OpCodes.Call, module.Import(typeof(object).GetConstructor(Array.Empty<Type>())))); il.Append(il.Create(OpCodes.Nop)); il.Append(il.Create(OpCodes.Ret)); programType.Methods.Add(ctor); // define the 'Main' method and add it to 'Program' var mainMethod = new MethodDefinition("Main", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void); programType.Methods.Add(mainMethod); // add the 'args' parameter var argsParameter = new ParameterDefinition("args", Mono.Cecil.ParameterAttributes.None, module.Import(typeof(string[]))); mainMethod.Parameters.Add(argsParameter); // create the method body il = mainMethod.Body.GetILProcessor(); il.Append(il.Create(OpCodes.Nop)); il.Append(il.Create(OpCodes.Ldstr, "Hello World")); var writeLineMethod = il.Create(OpCodes.Call, module.Import(typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }))); // call the method il.Append(writeLineMethod); il.Append(il.Create(OpCodes.Nop)); il.Append(il.Create(OpCodes.Ret)); // set the entry point and save the module myHelloWorldApp.EntryPoint = mainMethod; myHelloWorldApp.Write("HelloWorld.exe"); 
+8
source

I am here without a laptop (I am walking down the street), so I cannot write and show you a complete example, but it is simple, like the other examples that you have already seen. but in addition to reading an existing assembly, you need to create it and save it.

You need to create AssemblyDefinition, ModuleDefinition, Type and Method and save it to disk.

You need to remember that its IL and metadata writer without a compiler.

Check this one , for example.

+1
source

All Articles