How to Save an Expression Tree as the Main Entry Point to a New Executable Disk File?

后端 未结 1 2018
南旧
南旧 2021-02-09 20:17

I\'m trying to export an expression tree to a PE assembly as the main entry point. I\'ve acquired a Lambda Expression through building an expression tree, for example:

<
1条回答
  •  我在风中等你
    2021-02-09 20:45

    Instead of just using Expression.Compile, use Expression.CompileToMethod(MethodBuilder).

    Short but complete example which creates an executable on disk, with the expression tree as the code executed in the entry point:

    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Linq.Expressions;
    
    class Program
    {
        static void Main()
        {
            var asmName = new AssemblyName("Foo");
            var asmBuilder = AssemblyBuilder.DefineDynamicAssembly
                (asmName, AssemblyBuilderAccess.RunAndSave);
            var moduleBuilder = asmBuilder.DefineDynamicModule("Foo", "Foo.exe");
    
            var typeBuilder = moduleBuilder.DefineType("Program", TypeAttributes.Public);
            var methodBuilder = typeBuilder.DefineMethod("Main",
                MethodAttributes.Static, typeof(void), new[] { typeof(string) });
    
            Expression action = () => Console.WriteLine("Executed!");
    
            action.CompileToMethod(methodBuilder);
    
            typeBuilder.CreateType();
            asmBuilder.SetEntryPoint(methodBuilder);
            asmBuilder.Save("Foo.exe");
        }
    }
    

    0 讨论(0)
提交回复
热议问题