private static unsafe void TestTypeEquivalenceWithTypePunning() { Console.WriteLine($"{nameof(TestTypeEquivalenceWithTypePunning)}"); { Console.WriteLine($"-- GetFunctionPointer()"); IntPtr fptr = typeof(CreateFunctionPointer).GetMethod("For_1").MethodHandle.GetFunctionPointer(); Assert.NotEqual(IntPtr.Zero, fptr); var s = new OnlyLoadOnce_1() { Field = 0x11 }; int res = ((delegate * < OnlyLoadOnce_1, int >)fptr)(s); Assert.Equal(s.Field, res); } { Console.WriteLine($"-- Ldftn"); IntPtr fptr = CreateFunctionPointer.For_2_Ldftn(); Assert.NotEqual(IntPtr.Zero, fptr); var s = new OnlyLoadOnce_2() { Field = 0x22 }; int res = ((delegate * < OnlyLoadOnce_2, int >)fptr)(s); Assert.Equal(s.Field, res); } { Console.WriteLine($"-- Ldvirtftn"); IntPtr fptr = CreateFunctionPointer.For_3_Ldvirtftn(out object inst); Assert.NotEqual(IntPtr.Zero, fptr); var s = new OnlyLoadOnce_3() { Field = 0x33 }; int res = ((delegate * < object, OnlyLoadOnce_3, int >)fptr)(inst, s); Assert.Equal(s.Field, res); } }
public static int GetField_2(OnlyLoadOnce_2 s) { return(s.Field); }