Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking a .NET Expression Tree into a new assembly

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.

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?

like image 734
Tamas Czinege Avatar asked Oct 24 '09 18:10

Tamas Czinege


1 Answers

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

lambdaExpression.CompileToMethod(myMethodBuilder);
like image 190
Tamas Czinege Avatar answered Nov 07 '22 17:11

Tamas Czinege