Generate exe in .Net

Posted by rwallace on Stack Overflow See other posts from Stack Overflow or by rwallace
Published on 2010-04-08T15:30:21Z Indexed on 2010/04/08 15:33 UTC
Read the original article Hit count: 425

Filed under:
|
|

In .Net, you can generate byte code in memory, and presumably save the resulting program to a .exe file. To do the first step, I have the following test code adapted from http://www.code-magazine.com/Article.aspx?quickid=0301051

var name = new AssemblyName();
name.Name = "MyAssembly";
var ad = Thread.GetDomain();
var ab = ad.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
var mb = ab.DefineDynamicModule("MyModule");
var theClass = mb.DefineType("MathOps", TypeAttributes.Public);
var retType = typeof(System.Int32);
var parms = new Type[2];
parms[0] = typeof(System.Int32);
parms[1] = typeof(System.Int32);
var meb = theClass.DefineMethod("ReturnSum", MethodAttributes.Public, retType, parms);
var gen = meb.GetILGenerator();
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Ldarg_2);
gen.Emit(OpCodes.Add_Ovf);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Br_S);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ret);
theClass.CreateType();

How do you do the second step, and save the result to a .exe?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET