开发者

Run-time Generation Compilation of CLR

I have a C# application which generates .NET functions at run-time and executes them. To do so, it generates C# in strings and calls the online C# compiler to convert it into CLR to be JIT compiled and executed.

For performance reasons, I would like to be able to generate directly CLR (in strings or through an internal representation) and execute it without using any compiler (but perhaps the JIT c开发者_开发技巧ompiler).

Is that possible ? I've seen some articles about code injection, but that doesn't exactly fits the bill.

Thank you !


I suspect that System.Reflection.Emit is what you're after. In particular, if you only want to generate a single method, I believe you should look at DynamicMethod. You can ask it to create an ILGenerator, build the IL, and then it will be JIT compiled when you convert the method into a delegate.

I don't believe you can just give it textual IL though... you'll be using the API, explicitly building various instructions. There may be an IL parser which uses this though...


If you just want to create .Net functions, Expression trees are the way to go. If you want to make a whole class, you can use Reflection.Emit, but then you're writing assembly code.

If you wait for .Net 5, maybe they will have a version of the compiler that you can pass arbitrary C# code to, but for now maybe you can use something that uses the DLR (like IronPython) to pass actual source code to.


I may not understand the question, but couldn't you, instead of generating C# code from your application, actually generate the equivalent intermediate language (IL) code that the C# compiler would generate anyway? Then you could just run the IL code directly without having to compile it first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜