An Introduction to CIL - Back to Hello World
(Page 4 of 4 )
Returning to the “hello world” example, it's now clear what we have to do. First, we have to push a string onto the stack -- “Hello World.” Then, we simply call the WriteLine method, specifying that we have a string as the sole argument. So, let's write a short program using the techniques we've learned so far. First comes the class and the method. We also have to put the required bit at the beginning. Put everything in a file called “helloworld.il”:
.assembly extern mscorlib {}
.assembly HelloWorld {}
.class public HelloWorld
{
.method public static void Main(string[] args)
{
.entrypoint
...
}
}
Now, we have to push the string that we're working with onto the stack in order for it to be passed in our call to WriteLine:
ldstr "Hello, World."
WriteLine can now be called. The above string will be popped off the stack, and WriteLine will print it onto the screen:
call void [mscorlib]System.Console::WriteLine(string)
We're still not done, however. There are two things that need to be taken care of. First, in order for a method to work properly in CIL, we need the explicitly set the maximum size of the stack. That is, we must state the most number of items that will be on the stack at any one time. In our example, we're only pushing one item onto the stack at a time, obviously:
.maxstack 1
Second, we have to add a return statement. In C#, this isn't necessary for a void method, but in CIL, we have to take care of this ourselves. Fortunately, it's easy enough:
ret
So, here's our completed “helloworld.il” program:
.assembly extern mscorlib {}
.assembly HelloWorld {}
.class public HelloWorld
{
.method public static void Main(string[] args)
{
.entrypoint
.maxstack 1
ldstr "Hello, World."
call void [mscorlib]System.Console::WriteLine(string)
ret
}
}
In order to be able to execute our program, we must first assemble it. This is done using ilasm.exe, which you should find in C:WINDOWSMicrosoft.NETFrameworkvX.x:
> C:pathtoilasm.exe helloworld.il
The program can now be executed:
> helloworld.exe
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |