/
codegen.cs
49 lines (42 loc) · 1.92 KB
/
codegen.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Reflection;
using System.Reflection.Emit;
class CGen {
public static int Main() {
AssemblyBuilder abuilder;
ModuleBuilder mbuilder;
TypeBuilder tbuilder;
FieldBuilder fbuilder;
PropertyBuilder pbuilder;
AssemblyName an;
String name = "tcgen.exe";
MethodBuilder method, get_method;
TypeAttributes attrs = TypeAttributes.Public | TypeAttributes.Class;
MethodAttributes mattrs = MethodAttributes.Public | MethodAttributes.Static;
byte[] body = {0x16, 0x2a}; // ldc.i4.0 ret
an = new AssemblyName ();
an.Name = name;
abuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save);
mbuilder = abuilder.DefineDynamicModule (name, name);
tbuilder = mbuilder.DefineType ("Test.CodeGen", attrs);
Type result = typeof(int);
Type[] param = new Type[] {typeof (String[])};
method = tbuilder.DefineMethod("Main", mattrs, result, param);
method.CreateMethodBody (body, body.Length);
fbuilder = tbuilder.DefineField ("int_field", typeof(int), FieldAttributes.Private);
fbuilder = tbuilder.DefineField ("string_field", typeof(string), FieldAttributes.Public);
/*pbuilder = tbuilder.DefineProperty ("FieldI", PropertyAttributes.None, typeof(int), null);
get_method = tbuilder.DefineMethod("get_FieldI", MethodAttributes.Public, result, null);
get_method.CreateMethodBody (body, body.Length);
pbuilder.SetGetMethod (get_method);*/
Type t = tbuilder.CreateType ();
abuilder.SetEntryPoint (method);
abuilder.Save (name);
Console.WriteLine ("abuilder == module.assembly: {0}", abuilder == mbuilder.Assembly);
Console.WriteLine ("abuilder == type.assembly: {0}", abuilder == t.Assembly);
Console.WriteLine ("abuilder == tbuilder.assembly: {0}", abuilder == tbuilder.Assembly);
Console.WriteLine ("mbuilder == type.Module: {0}", mbuilder == t.Module);
Console.WriteLine ("mbuilder == tbuilder.Module: {0}", mbuilder == tbuilder.Module);
return 0;
}
}