如何使用Mono.Cecil创建HelloWorld.exe [英] How to use Mono.Cecil to create HelloWorld.exe

查看:284
本文介绍了如何使用Mono.Cecil创建HelloWorld.exe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Mono.Cecil从头开始创建简单的程序?到目前为止,我已经找到了所有示例和教程,假定您正在使用现有的程序集,正在阅读或进行小的更改。

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

推荐答案

请参见以下代码以开始使用:

See the following code to get you started:

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's 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");

这篇关于如何使用Mono.Cecil创建HelloWorld.exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆