C# Scripts using DynamicMethod

C#으로 Script를 구동하도록 만들어진 훌륭한 소스다
향후 유용하게 사용될 수 있겠다.


I had the problem to host active content in my document files, which included small scripts for animations and object specific interactions, like JavaScripts in HTML.
C# offers the great possibility to compile your own assemblies at runtime. However, there is no possibility to unload such compilations, to unload dynamic generated assemblies at runtime. The only way to do this is to create such assemblies in your own Domain and to unload such Domains later on but the communication between Domains is slow like inter process communication. Additional, to load the C# compiler environment and the compilation itself is not very fast at runtime, not nice for documents with hundreds of small internal scripts.
There are already quite a few articles about dynamic code generation using .NET and how to ship around these problems, but nothing was good enough for my case. The idea was to write my own C# script compiler based on C# syntax and conventions and to use Dynamic Methods to generate IL for best performance.
I found out that this works well without any assembly generation. With such solution, it is possible to use all existing classes and value structures but it is not possible to define your own new classes. The reason for this is that a .NET class always needs an assembly and the related assembly information.
However, the script itself works like a unique class with member functions and variables.

Using the Demo

For demonstration purposes, I wrote a small and very limited test program, only three C# files:
Program.cs contains a very simple user interface and EditCtrl.cs a simple code editor control.
The file Script.cs contains the class Script and this class is easy to use in other C# projects.
The demo looks like this and can be used to check and debug functionality and speed, the directory Demos contains some demo scripts for this.

Using the Code

To use the code in other C# projects, it is only necessary to import the class Script from Script.cs. After this is done, it’s possible to use the Script class like this:

var script = new Script();
script.Code = "using System.Windows.Forms; MessageBox.Show(\"Hello World!\");";

The second line in Script.cs contains the expression #define TraceOpCode. If this is defined (currently only in DEBUG), the Debug Output window will show the current MSIL output.
For this simple example, it is only:

ldstr Hello World!
call System.Windows.Forms.DialogResult Show(System.String)

How It Works

The namespace System.Reflection.Emit contains the class DynamicMethod. This class exists since .NET FrameWork version 2.0.
It is possible to use the DynamicMethod class to generate and execute methods at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. Dynamic methods are the most efficient way to generate and execute small amounts of code. A good reference of how to use and an example code can be found here.
The Script class encapsulates a simple array of Dynamic methods: DynamicMethod[] methods. Every scriptfunction and the script body as creator is compiled to one of the dynamic methods in this array.
For this, the Script class contains the private helper class Script.Compiler to translate the script code to MSIL instructions using the ILGenerator from DynamicMethod.
After this own compilation, the .NET Framework just-in-time (JIT) compiler can translate the MSIL instructions to native machine code.
In difference to script interpreters, we get fast machine code for each supported CPU architecture.

“C# Scripts using DynamicMethod”의 32개의 댓글

  1. Good day! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in trading links or maybe guest writing a blog post
    or vice-versa? My website covers a lot of the
    same subjects as yours and I feel we could greatly benefit from each other.
    If you might be interested feel free to send me an e-mail.

    I look forward to hearing from you! Great blog by the way!

  2. Magnificent goods from you, man. I’ve understand your stuff previous to and you’re just extremely excellent.
    I actually like what you have acquired here, really like what
    you are saying and the way in which you say it.
    You make it enjoyable and you still care for to keep it smart.
    I can’t wait to read far more from you. This is really a terrific website.

  3. I really love your blog.. Excellent colors & theme.
    Did you develop this site yourself? Please reply back as I’m hoping to create my own site
    and would like to find out where you got this from or exactly what the theme is named.

  4. I simply want to say I am just new to weblog and truly liked you’re web site. Probably I’m likely to bookmark your blog post . You surely have impressive well written articles. Bless you for revealing your webpage.

  5. When I originally commented I clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I recieve four emails with similar comment. Can there be any way it is possible to eliminate me from that service? Thanks!

  6. Hmm is anyone else encountering problems with the pictures on this blog loading?
    I’m trying to figure out if its a problem on my end or if it’s the blog.
    Any suggestions would be greatly appreciated.

  7. Youre so trendy! I don’t mean Ive check out anything similar to this before. So good to discover someone with some original ideas on this subject. realy thanks for beginning this up. this internet site is something that is required on the internet, somebody with a little originality. valuable work for bringing something new to the internet!

  8. The next time I review a blog site, I hope that it doesn’t dissatisfy me as much as this one. I mean, I understand it was my choice to read, however I actually assumed youd have something intriguing to state. All I hear is a lot of whimpering regarding something that you can take care of if you werent too active trying to find attention.

  9. When I initially commented I clicked the -Inform me when new remarks are included- checkbox and now each time a remark is added I obtain four emails with the very same comment. Is there any way you can eliminate me from that solution? Many thanks!

  10. This is the appropriate blog for any person that wants to learn about this subject. You understand so much its almost hard to say with you (not that I really would want?HaHa). You certainly put a new spin on a topic thats been blogged about for years. Fantastic things, simply wonderful!

  11. I am usually to blog writing and also i really appreciate your material. The short article has really peaks my passion. I am going to bookmark your website and also maintain looking for new info.

  12. Place on with this review, I truly believe this site requires much more factor to consider. I?ll probably be again to check out a lot more, many thanks for that information.

  13. This is the appropriate blog for any person that intends to discover this topic. You realize so much its almost tough to suggest with you (not that I in fact would want?HaHa). You most definitely placed a new spin on a subject thats been covered for several years. Great things, simply excellent!

  14. After I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Perhaps there is a way you can remove me from that service? Cheers!

  15. When I originally commented I clicked the -Notify me when brand-new remarks are included- checkbox and also now each time a remark is added I obtain 4 e-mails with the very same comment. Is there any way you can eliminate me from that solution? Thanks!

댓글 남기기