如何将表达式树保存为新的可执行文件的主入口点? [英] How to Save an Expression Tree as the Main Entry Point to a New Executable Disk File?

查看:126
本文介绍了如何将表达式树保存为新的可执行文件的主入口点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将表达式树导出到PE程序集作为主要入口点。我通过构建表达式树获取了一个Lambda表达式,例如:

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:

using System.Linq;
using System;

// 1. use expression trees to create a block expression (not shown)

// 2. create a lambda expression: 
LambdaExpression exprLambda = Expression.Lambda(exprBlock, new ParameterExpression[0]);

MethodBuilder mbuilder = null;
// 3. ??? Somehow get a method builder instance that works ??? 

// 4. Compile the lambda using the MethodBuilder instance. 
exprLambda.CompileToMethod(mbuilder);

// 5. ??? Somehow get an AssemblyBuilder instance to .Save(..) this to disk.  ??? 

步骤3和5是我所缺少的东西。

Steps 3 and 5 are what I'm missing.

推荐答案

而不是仅使用 Expression.Compile ,请使用 Expression.CompileToMethod(MethodBuilder)

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> action = () => Console.WriteLine("Executed!");

        action.CompileToMethod(methodBuilder);

        typeBuilder.CreateType();
        asmBuilder.SetEntryPoint(methodBuilder);
        asmBuilder.Save("Foo.exe");
    }
}

这篇关于如何将表达式树保存为新的可执行文件的主入口点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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