An Introduction to CIL - A Short Interruption
(Page 3 of 4 )
Before we continue with our main conversion task, let's break off for a second, temporarily turning our program into a “hello world” example, just to explore some basic concepts without taking a dive (otherwise, with our example, it is quite a dive).
With C#, operations and method calls are all quite readable – the syntax all makes sense and is what we're used to. CIL, however, is quite different. Up until now, CIL wasn't too different from C#. Now, however, some clear differences will appear. To perform operations, programs use what is called a stack. Basically, first, values are pushed onto the stack. Then, some sort of operation is performed which involves popping those values off of the stack and, if applicable, pushing a result back onto the stack. For example, consider addition. Let's add the numbers three and four together. First, we push three onto the stack:
3
Then, we push four onto the stack:
4
3
Notice how it is stacked on top of the previous value. Now, in order to perform the addition, we need to take both values off of the stack, add them up, and then push the value onto the stack. After that's done, the stack looks like this:
7
Now we have the result. Let's turn to a more complicated example: a method call. Consider the following method call in C#:
Console.WriteLine("Two numbers: {0} and {1}", 73, 82);
C# makes this easy, but how does this look in CIL when we compile it? The resulting code seems quite scary:
ldstr "Two numbers: {0} and {1}"
ldc.i4.s 73
box [mscorlib]System.Int32
ldc.i4.s 82
box [mscorlib]System.Int32
call void [mscorlib]System.Console::WriteLine(string, object, object)
It only seems scary, though. Let's take it line-by-line and examine what it does to the stack. The first line starts with ldstr, which stands for “load string.” As its name suggests, it loads a string onto the stack. So, after it's executed, the stack looks like this:
“Two numbers: {0} and {1}”
The next line isn't any scarier. It loads the number 73 onto the stack. The stack now looks like this:
73
“Two numbers: {0} and {1}”
After that, we box the number at the top of the stack (73), turning it into an Int32:
73 (Int32 object)
“Two numbers: {0} and {1}”
The next two lines are very similar, and after they are executed, the stack looks like this:
82 (Int32 object)
73 (Int32 object)
“Two numbers: {0} and {1}”
Now, the final line is where the action takes place. We call the WriteLine method of System.Console. Note that we have to specify the parameters of the method we want – this is important! Here, we specify that we want the WriteLine method that takes a string and then two objects. When this line is executed, an object is first popped off of the stack, followed by another object and then finally a string. Notice how this is done in reverse order – this, too, is important!
Next: Back to Hello World >>
More ASP.NET Articles
More By Peyton McCullough