Free mag vol1 | Page 738

CHAPTER 18  UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES stloc.0 // Now load the value of the currSpeed field and get its string // representation (note call to ToString()). ldarg.0 ldflda int32 CILCars.CILCar::currSpeed call instance string [mscorlib]System.Int32::ToString() ldloc.0 // Now call the MessageBox.Show() method with loaded values. call valuetype [System.Windows.Forms] System.Windows.Forms.DialogResult [System.Windows.Forms] System.Windows.Forms.MessageBox::Show(string, string) pop ret } } Although the amount of CIL code is a bit more than you see in the implementation of CILCar, things are still rather straightforward. First, given that you are defining a static method, you don’t have to be concerned with the hidden object reference (thus, the ldarg.0 opcode really does load the incoming CILCar argument). The method begins by loading a string ("{0}'s speed is") onto the stack, followed by the CILCar argument. After these two values are in place, you load the value of the petName field and call the static System.String.Format() method to substitute the curly bracket placeholder with the CILCar’s pet name. The same general procedure takes place when processing the currSpeed field, but note that you use the ldflda opcode, which loads the argument address onto the stack. At this point, you call System.Int32.ToString() to transform the value at said address into a string type. Finally, after both strings have been formatted as necessary, you call the MessageBox.Show() method. At this point, you are able to compile your new *.dll using ilasm.exe with the following command: ilasm /dll CILCars.il and verify the contained CIL using peverify.exe, as follows: peverify CILCars.dll Building CILCarClient.exe Now you can build a simple *.exe assembly with a Main() method that will • Make a CILCar object. • Pass the object into the static CILCarInfo.Display() method. Create a new file named CarClient.il and define external references to mscorlib.dll and CILCars.dll (don’t forget to place a copy of this .NET assembly in the client’s application directory!). Next, define a single type (Program) that manipulates the CILCars.dll assembly. Here’s the complete code: // External assembly refs. .assembly extern mscorlib { 681