Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Welcome Guest | Log In | Register | Benefits
Channels ▼
RSS

Generating Code at Run Time With Reflection.Emit


Generating Code at Run Time With Reflection.Emit

Listing 1: The HelloReflectionEmit class

using System;
using System.Reflection;
using System.Reflection.Emit;

class HelloReflectionEmit
{
    static void Main()
    {
        // Create a (weak) assembly name
        AssemblyName an = new AssemblyName();
        an.Name = "HelloReflectionEmit";

        // Define a new dynamic assembly (to be written to disk)
        AppDomain ad = AppDomain.CurrentDomain;
        AssemblyBuilder ab = 
            ad.DefineDynamicAssembly(an, 
            AssemblyBuilderAccess.Save);

        // Define a module for this assembly
        ModuleBuilder mb = ab.DefineDynamicModule(an.Name, 
            "Hello.exe");

        // namespace Foo { public class Bar { ... } }
        TypeBuilder tb = mb.DefineType("Foo.Bar", 
            TypeAttributes.Public|
            TypeAttributes.Class);

        // The leg bone's connected to the knee bone...
        MethodBuilder fb = tb.DefineMethod("Main", 
            MethodAttributes.Public|
            MethodAttributes.Static, 
            typeof(int), 
            new Type[] {typeof(string[])});

        // Write the ubiquitous "Hello, World!" method, in IL
        ILGenerator ilg = fb.GetILGenerator();

        ilg.Emit(OpCodes.Ldstr, "Hello, World!");
        ilg.Emit(OpCodes.Call, 
            typeof(Console).GetMethod("WriteLine", 
                new Type[] {typeof(string)} ));

        ilg.Emit(OpCodes.Ldc_I4_0);
        ilg.Emit(OpCodes.Ret);

        // Seal the lid on this type
        Type t = tb.CreateType();

        // Set the entrypoint (thereby declaring it an EXE)
        ab.SetEntryPoint(fb,PEFileKinds.ConsoleApplication);

        // Save it
        ab.Save("Hello.exe");

        // Done!
        Console.WriteLine("File saved: {0}", "Hello.exe");
    }
}


Related Reading


More Insights