Skip to main content

Posts

Showing posts from January, 2008

ILCode for newobj by creating a new custom Type

AssemblyName _assemblyName = new AssemblyName();
_assemblyName.Name = "newObj";
AssemblyBuilder _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder _modBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name + ".exe");
TypeBuilder _typeBuilder = _modBuilder.DefineType(" ILCode.Program");

TypeBuilder _customType = _modBuilder.DefineType("ILCode.myCustomType", TypeAttributes.Public);

Type[] arg = { typeof(string) };
ConstructorBuilder _customTypeConstructor = _customType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, arg);
PropertyBuilder _prop1 = _customType.DefineProperty("MyId", PropertyAttributes.None, typeof(int), new Type[0]);
PropertyBuilder _prop2 = _customType.DefineProperty("MyName", PropertyAttributes.None, typeof(…

MSIL Hello World

AssemblyName _assemblyName = new AssemblyName();
_assemblyName.Name = "helloWorld";
AssemblyBuilder _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);

ModuleBuilder _modBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name+ ".exe");

TypeBuilder _typeBuilder = _modBuilder.DefineType("Foo");


MethodBuilder _methodBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
ILGenerator _il = _methodBuilder.GetILGenerator();

_il.EmitWriteLine("hello World ");
_il.Emit(OpCodes.Ret);

_typeBuilder.CreateType();
_modBuilder.CreateGlobalFunctions();
_assemblyBuilder.SetEntryPoint(_methodBuilder, PEFileKinds.ConsoleApplication);
_assemblyBuilder.Save(_assemblyName.Name + ".exe");
_il = null;

MSIL IF Statement

This example shows you how to generate IL for a simple IF statement

Code in C#

int x = 1000;
if (x > 2000)
Console.WriteLine("Hey There");

Using Reflection Emit

AssemblyName _assemblyName = new AssemblyName();
_assemblyName.Name = "ifS";
AssemblyBuilder _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);

ModuleBuilder _modBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name + ".exe", true);
TypeBuilder _typeBuilder = _modBuilder.DefineType("IfType");

MethodBuilder _methodBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);

ILGenerator _il = _methodBuilder.GetILGenerator();

LocalBuilder _intName = _il.DeclareLocal(typeof(int));
Label body = _il.DefineLabel();

_il.Emit(OpCodes.Ldc_I4, 1000);
_il.Emit(OpCodes.Stloc_0);
_il.Emit(OpCodes.Ldloc_0);
_il.Emit(OpCodes.Ldc_I4, 2000);
_il.Emit(OpCodes.Blt, body);