Ejemplo n.º 1
0
        /// <summary>获取方法在JIT编译后的地址(JIT Stubs)</summary>
        /// <remarks>
        /// MethodBase.DeclaringType.TypeHandle.Value: 指向该类型方法表(编译后)在 JIT Stubs 的起始位置。
        /// Method.MethodHandle.Value: 表示该方法的索引序号。
        /// CLR 2.0 SP2 (2.0.50727.3053) 及其后续版本中,该地址的内存布局发生了变化。直接用 "Method.MethodHandle.Value + 2" 即可得到编译后的地址。
        /// </remarks>
        /// <param name="method"></param>
        /// <returns></returns>
        unsafe public static IntPtr GetMethodAddress(MethodBase method)
        {
            // 处理动态方法
            if (method is DynamicMethod)
            {
                var ptr = (byte*)((RuntimeMethodHandle)method.GetValue("m_method")).Value.ToPointer();

                // 确保方法已经被编译
                RuntimeHelpers.PrepareMethod(method.MethodHandle);

                if (IntPtr.Size == 8)
                    return new IntPtr((ulong*)*(ptr + 5) + 12);
                else
                    return new IntPtr((uint*)*(ptr + 5) + 12);
            }

            ShowMethod(new IntPtr((int*)method.MethodHandle.Value.ToPointer() + 2));
            // 确保方法已经被编译
            RuntimeHelpers.PrepareMethod(method.MethodHandle);
            ShowMethod(new IntPtr((int*)method.MethodHandle.Value.ToPointer() + 2));

            return new IntPtr((int*)method.MethodHandle.Value.ToPointer() + 2);
        }