An Introduction to CIL
(Page 1 of 4 )
CIL stands for Common Intermediate Language. It is used to help make programs cross-platform compatible. This article, the first of two parts, will introduce you to CIL and show you how to use it.
With .NET, a program is usually written in a language such as C# or Visual Basic and is then compiled. However, the source code of the program is not directly compiled into native code. Rather, it is compiled into Common Intermediate Language (CIL), also known as Microsoft Intermediate Language (MSIL). Then, when the resulting executable file is executed, the intermediate code is translated into native code. This process, which is similar to the process a Java application goes through, has the advantage of cross-platform compatibility.
Of course, one need not know too much about CIL in order to develop applications in .NET. However, CIL is human-readable, and it's possible to work directly with it. In this article, we'll take a quick look at CIL.
A Conversion Task
In order to become familiar with the very basics (the scope of this article) of CIL, let's examine a program in C# and then work to convert it into CIL. Let's use a program that finds prime numbers between two and one million:
using System;
public class FindPrimes
{
public static void Main(string[] args)
{
for (int i = 2; i <= 1000000; i++)
{
bool prime = true;
int limit = (int)Math.Sqrt(i);
for (int f = 2; f <= limit; f++)
{
if (i % f == 0)
{
prime = false;
break;
}
}
if (prime)
{
Console.WriteLine(i);
}
}
Console.WriteLine("Done!");
}
}
The program is simple. We first set up an outside loop with loops over the numbers two through one million. Inside of this loop, we assume that each number is prime to begin with. We then loop over all the numbers from two to the square root of the number being examined. If the number being examined for primality is divisible by any of the numbers from the inner loop (that is, if it has no remainder), then the number is not prime, and we may safely break out of the inner loop in order to begin testing the primality of a new number. Of course, if the inner loop runs completely through, then the number is prime, and we print it. At the end of everything, we print out a message and exit.
We'll now break up our short program and convert it into CIL step-by-step. The first thing we see in the program is a using statement. Statements like this one, however, only exist for convenience and have no equivalent in CIL. Before we move on, though, we have to do a little setting up. Create a file and name it what you will, giving it a “.il” extension. Now, paste the following into it:
.assembly extern mscorlib {}
.assembly FindPrimes {}
This is a necessary step. Ordinarily, when compiling a program from a higher-level language, the compiler would add some more meat here, but for our purposes, that isn't necessary – the assembler will take care of what we need.
Next: Classes >>
More ASP.NET Articles
More By Peyton McCullough