CHAPTER 15 UNDERSTANDING CIL AND THE (Web hosting providers) 506
Thursday, January 31st, 2008CHAPTER 15 UNDERSTANDING CIL AND THE 506 THE ROLE OF DYNAMIC ASSEMBLIES In general, the types of the System.Reflection.Emit namespace allow you represent raw CIL tokens programmatically during the construction of your dynamic binary. You will see many of these members in the example that follows; however, the ILGenerator type is worth checking out straightaway. The Role of the System.Reflection.Emit.ILGenerator As its name implies, the ILGenerator type s role is to inject CIL opcodes into a given type member. Typically, you will not need to directly create ILGenerator objects, but rather receive a valid reference to the ILGenerator type using the builder-centric types (such as the MethodBuilder and ConstructorBuilder types), for example: // Obtain an ILGenerator from a ConstructorBuilder // object named ‘myCtorBuilder’. ConstructorBuilder myCtorBuilder = new ConstructorBuilder(/* …various args… */); ILGenerator myCILGen = myCtorBuilder.GetILGenerator(); Once you have an ILGenerator in your hands, you are then able to emit the raw CIL opcodes using any number of methods. Table 15-9 documents some (but not all) methods of ILGenerator. Table 15-9. Select Methods of ILGenerator Method Meaning in Life BeginCatchBlock() Begins a catch block BeginExceptionBlock() Begins an exception block for a nonfiltered exception BeginFinallyBlock() Begins a finally block BeginScope() Begins a lexical scope DeclareLocal() Declares a local variable DefineLabel() Declares a new label Emit() Is overloaded numerous times to allow you to emit CIL opcodes EmitCall() Pushes a call or callvirt opcode into the CIL stream EmitWriteLine() Emits a call to Console.WriteLine() with different types of values EndExceptionBlock() Ends an exception block EndScope() Ends a lexical scope ThrowException() Emits an instruction to throw an exception UsingNamespace() Specifies the namespace to be used in evaluating locals and watches for the current active lexical scope The key method of ILGenerator is Emit(), which works in conjunction with the System.Reflection. Emit.OpCodes class type. As mentioned earlier in this chapter, this type exposes a good number of read-only fields that map to raw CIL opcodes. The full set of these members are all documented within online help, and you will see various examples in the pages that follow. Emitting a Dynamic Assembly To illustrate the process of defining a .NET assembly at runtime, let s walk through the process of creating a single-file dynamic assembly named MyAssembly.dll. Within this module is a class named HelloWorld. The HelloWorld type supports a default constructor and a custom constructor that is used to assign the value of a private member variable (theMessage) of type string. In addition,
Check Tomcat Web Hosting services for best quality webspace to host your web application.