Skip to content

F# Metaprogramming part 3: Creating MSIL on the Fly

April 12, 2012

This post completes my 3-part series on F# metaprogramming:

  1. JITing and executing native machine code
  2. Compiling and executing synthetic F# code
  3. Creating and executing synthetic MSIL will be covered below

Our tiny synthetic snippet will be fun() -> System.Console.WriteLine(“Hello, world!”).

We begin with defining a delegate type having the target signature unit -> unit.

Then, we would need a reference to System.Console.WriteLine that we’ll get through reflection.

Then, the meat of the approach: we are creating a DynamicMethod placeholder for MSIL, then emit there necessary MSIL instructions, then wrap it up by creating a delegate for calling the synthetic MSIL.

Finally, we execute the method just synthesized by invoking this delegate.

// Creating MSIL on the fly
open System
open System.Reflection
open System.Reflection.Emit

// Type of method to be created
type HW = delegate of unit -> unit

// get MethodInfo of System.Console.WriteLine
let consoleWL = typeof<Console>.GetMethod("WriteLine", [| typeof<string> |])

// Synthesize a new method fun() -> Console.WriteLine("Hello, world!")
let synthMethod = new DynamicMethod("HelloWorld", null, ([| |]: Type []))
// The overload below limits MSIL length to 64 bytes only;
// Other non-limiting MSIL generator overload exists
let msilGen = synthMethod.GetILGenerator();
msilGen.Emit(OpCodes.Ldstr, "Hello, world!")
msilGen.Emit(OpCodes.Call, consoleWL)

// Now create delegate to execute created method and do invoke
let caller = synthMethod.CreateDelegate(typeof<HW>) : ?> HW

From → F#

One Comment

Trackbacks & Pingbacks

  1. F# Weekly #15, 2013 | Sergey Tihon's Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: