Add test for dynamic method resurrection.
[mono.git] / mono / tests / dynamic-method-resurrection.cs
1 using System;
2 using System.Reflection;
3 using System.Reflection.Emit;
4 using System.Runtime.InteropServices;
5 using System.Runtime.CompilerServices;
6
7 delegate int Getter ();
8
9 class Host {
10
11         static int Field = 42;
12
13         Getter g;
14
15         public Host (Getter g) {
16                 this.g = g;
17         }
18
19         ~Host () {
20                 Program.resed = g;
21         }
22 }
23
24
25 class Program {
26                 internal static Getter resed;
27                 static int result;
28                 static void DoStuff ()
29         {
30                         DynamicMethod method = new DynamicMethod ("GetField",
31                         typeof (int), new Type [0], Type.GetType ("Host"));
32
33                         ILGenerator il = method.GetILGenerator ();
34                         il.Emit (OpCodes.Ldsfld, typeof (Host).GetField ("Field", BindingFlags.Static | BindingFlags.NonPublic));
35                         il.Emit (OpCodes.Ret);
36
37                         var g = (Getter)method.CreateDelegate (typeof (Getter));                        
38                         new Host (g);
39         }
40
41                 static bool CheckStuff () {
42                         if (resed == null)
43                                 return false;
44                         Program.result = resed ();
45                         resed = null;
46                         return true;
47                 }
48
49                 public static int Main ()
50         {
51                         int cnt = 5;
52                         DoStuff ();
53                         do {
54                                 if (CheckStuff ())
55                                         break;
56                                 GC.Collect ();
57                                 GC.WaitForPendingFinalizers ();
58                         } while (cnt-- > 0);
59                         GC.Collect ();
60                         GC.WaitForPendingFinalizers ();
61                         return result == 42 ? 0 : 1;
62                 }
63 }