将.NET表达式树链接到新程序集中 [英] Linking a .NET Expression Tree into a new assembly

查看:53
本文介绍了将.NET表达式树链接到新程序集中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写自己的玩具My Toy Language-> MSIL编译器,以便更好地了解编译器的工作方式。我可以进行语法分析和词法分析,已经构建了表达式树,并使用System.Linq.Expressions表达式树API,我有一个有效的解释器。现在,我想发出一些真实的MSIL程序集。

I'm trying to write my own toy My Toy Language -> MSIL compiler in order to get a better understanding of how compilers work. I got the parsing and lexing working, I have built the expression trees and using the System.Linq.Expressions expression tree API, I have a working interpreter. Now I would like to emit some real MSIL assemblies.

问题是,我不知道如何实际构建这些程序集。 MethodBuilder 类仅接受原始的MSIL方法主体,因此我必须获取表达式树的原始MSIL。调用 Expression.Compile()返回一个有效的委托,但我不是能够获得其潜在的MSIL。调用 MethodInfo.GetMethodBody()会引发InvalidOperationException

The problem is, I can't figure out how to actually build these assemblies. The MethodBuilder class only accepts raw MSIL method bodies, so I have to get the raw MSIL of my expression tree. Calling Expression.Compile() returns a working delegate but I'm not able to get its underlying MSIL. Calling MethodInfo.GetMethodBody() throws an InvalidOperationException since it's not implemented in that specific child class.

如何将该委托链接到新程序集中?

How can I link that delegate into a new assembly?

推荐答案

刚刚找到了它。 DLR版本的LambdaExpression公开了完全满足我需要的CompileToMethod方法。

Just found it. The DLR version of LambdaExpression exposes a CompileToMethod method which does exactly what I need.

lambdaExpression.CompileToMethod(myMethodBuilder);

这篇关于将.NET表达式树链接到新程序集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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