Reflection Emit

ReflectionEmit is a part of the DotNet framework that allows the creation of new code at runtime. You can generate EXEs and DLLs and save them to disk, or you can create functions and classes for immediate use. The generated functions are compiled with the same JIT compiler as anything else in DotNet, and therefore run with equivalent performance.

ReflectionEmit requires you to emit MicrosoftIntermediateLanguage (IL). Generated IL can be difficult to debug, because it is always JIT-compiled and never interpreted. There is (currently) no debugger that shows the state of the virtual machine and allows a programmer to single-step through the IL instructions. (However, there are reports that if you disassemble any DLL with ildasm, then reassemble it with ilasm /debug, ilasm will generate step-by-step debugging information, so you can step through the code in Visual Studio.) It is very easy (using ILGenerator) to create invalid sequences of instructions, and sometimes very hard to see what is invalid about them.

A program called ILDASM (IL disassembler) ships with the DotNet framework and allows EXEs and DLLs to be inspected. It is common for programmers to learn what instructions to emit by writing equivalent C# or VB code and looking at the IL generated by the compiler. It is also possible to debug code generators by saving the generated code to disk for the sole purpose of inspecting it with ILDASM.

Microsoft's code generates IL behind the scenes when compiling regular expressions.

LINQ Expression Trees can also be compiled to executable code in a way that uses IL behind the scenes, but compiled Expression Trees cannot be saved to disk as EXEs or DLLs.

DotNet allows you to load a DLL from a byte array, but ReflectionEmit spares you the trouble of generating the byte array.

Java allows you to load a Java class from a byte array, but the standard Java libraries do not have facilities to aid in the construction of a suitable byte array. However, the bytecode format is well documented, and there are third-party libraries such as ASM (http://asm.ow2.org/), and the older BCEL (http://jakarta.apache.org/bcel/), that can do the job.


CategoryDotNet


EditText of this page (last edited March 9, 2011) or FindPage with title or text search