Friday, March 20, 2009

MSIL : Running MSIL code inside Visual Studio

Using Visual Studio 2005.

Project Create - choose Visual C++ and then "Makefile Project".

This simple example will add two numbers so call the project AddTwoNum.

This bring up a wizard.

Click "Next". For Debug settings, in the "Build Command Line" type:

build.bat

Then click "Finish".

In the Solution Explorer, delete "readme.txt".

Add a text file called "Build.bat" to the project.

It contains:

ilasm /nologo /debug AddTwoNum.il


(ilasm is the command line MSIL assembler).

Add a text file called "AddTwoNum.il" to the project.

It contains:

.assembly AddTwoNum {}

.method static public void main() il managed
{
.entrypoint

.maxstack 10

.locals init (int32 firstNum,
int32 secondNum,
int32 resultNum)

ldc.i4 11
stloc firstNum
ldc.i4 22
stloc secondNum
ldloc firstNum
ldloc secondNum
add
stloc resultNum

ldstr "{0} + {1} = {2}"

ldloc firstNum
box int32

ldloc secondNum
box int32

ldloc resultNum
box int32

call void [mscorlib]System.Console::WriteLine(string, object, object, object)

// This bit just waits for a key to keep the command line prompt open

ldstr "Press Enter to continue"
call void [mscorlib]System.Console::WriteLine(class System.String)

// Call the System.Console.Read function
call int32 [mscorlib]System.Console::Read()

// The pop instruction removes the top element from the stack.
// (remove number returned by Read() function)
pop

ret
}


Now press "F6". Project should assemble cleanly.

Press "F5" to run it.

Answer "Yes" to "The project is out of date - Rebuild?"

Command prompt will display:


11 + 22 = 33
Press Enter to continue


You can set breakpoints in the normal way, step through the code in the usual way and the "Locals" debug window will display the values of the three variables.

Enjoy!

2 comments:

Unknown said...

Hi ! Thanks for the useful post.

Could you please help me with debugging? Breakpoints don't seem to work. What I may be missing ?

I'm using VS 2010.

nzpcmad said...

Apologies.

I've never tried with VS 2010.

And I've "moved on" from that project so I no longer have the environment.