• 动态创建 Hello World


    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");
  • 相关阅读:
    3道常见的vue面试题,你都会了吗?
    如何让HTTPS站点评级达到A+? 还得看这篇HTTPS安全优化配置最佳实践指南
    Python速查表汇总
    VIM复健
    【PHP】使用RSA加密解密
    【PHP】生成RSA公钥私钥
    【PHP】生成验证码
    WebDriverManager实现自动获取浏览器驱动(Java)
    了解patchpackage
    github访问不了记录一下
  • 原文地址:https://www.cnblogs.com/nanfei/p/12123924.html
Copyright © 2020-2023  润新知