In part one I explained how to call a method from IL today I will show you how to define a local variable in IL and use it.
Here is the method that we will define in IL. There is no advantage of defining a method like this in IL but for this post it's sufficient
Code sample 2 is the code that generates code sample 1 at runtime here the explication what it does.
- (Line 1) Create an instance of the DynamicMethod Type so that it is possible to inject IL at runtime. The DynamicMethod needs to know the signature of the method this must be specified in the constructor. In this case the return type is void and it has no parameters.
- (Line 5) We need to define a local variable this can done by using the DeclareLocal method of the ILGenerator class. It requires the type of the local as a parameter. The local will be defined in the variable list at index 0.
- (Line 7) The ldstr opcode let push a string on the evaluation stack. In this case it put "this variable is defined in IL" on the evaluation stack.
- (Line 8) We need to store the string from Line 7 in the local variable this is possible by the Stloc opcode. In this case we use the Stloc_0 it is a shortcut to store the result in the variable list at index 0.
- (Line 9) We need to load the variable back on the evaluation stack so that we can call the the method WriteLine this can be done by using the LdLoc opcode.
- (Line 10) Emit an opcode so that it calls the WriteLine method.
- (Line 14) Invoke the method that is generated.
mrt 26 2008, 09:05