Microsoft Intermediate Language inline benutzen


Bis auf F# ist mir keine .NET Sprache bekannt bei der man IL Code direkt inline benutzen kann. Das hat Mike Stall nun mit seinem Tool geändert. Es ist nun durch einen kleinen “Hack” möglich IL Code direkt in praktisch jeder .NET Sprache zu verwenden:


“C# doesn’t support inline IL. As an experiment, I wrote a post-compiler tool that allows primitive IL inlining for C# / VB.Net (or any .net language). It also handles the pdbs properly, so you can even debug the IL snippets alongside the rest of the source code


ein kleines Beispiel:





using System;
class Program
{
static void Main()
{
int x = 3;
int y = 4;
int z = 5;

// Here’s some inline IL; “x=x+y+z”
#if IL
ldloc x
ldloc y
add
ldloc z
add
stloc x
#endif
Console.WriteLine(x);
}
}


Geil! kann ich da nur sagen!


“How does it work?


This IL inliner is really just a parlor trick. It’s just a post-compile tool which round trips the source through ilasm / ildasm, and injects the new IL in the middle.


Specifically



  • It compiles the original source using the high level compiler, such as C# / VB.Net. E.g.:
    csc %input_file% /debug+ /out:%temp_output%

    You’ll notice the IL snippets are conveniently under an #ifdef such that the compiler doesn’t get confused by it. This
    also introduces a key limitation which I’ll discuss below.

  • ILDasm the output. E.g.:
    ildasm %temp_output% /linenum /out=%temp_il_output%

  • Find the inline IL snippets in the original source. It turns out that ilasm is sufficiently intelligent that this is mainly just text processing. You could do it with a perl script.

  • Inject these snippets back into the ildasm output from step #2. Be sure to add .line directives to map the pdbs

  • run ilasm on the newly merged file.
    ilasm %temp_il_output% /output=%output_file% /optimize /debug

Quelle 1: http://research.microsoft.com/projects/ilx/fsharp.aspx
Quelle 2: http://blogs.msdn.com/jmstall/archive/2005/02/21/377806.aspx

Comments are closed.