我愿意使用unsafe
。如何获取类虚拟表地址并将其转换为 int?
最佳答案
(编辑:射击 - 忘了你还必须确保它不是内联的 - 见编辑)
你不需要 unsafe,但你确实需要确保方法已经过 JIT(.PrepareMethod
做的):
警告:我不完全确定(没有更多研究)这些数字的长期准确性;我知道它们曾经曾经是准确的,因为我曾经用它来运行时交换方法实现...嘘
using System;
using System.Runtime.CompilerServices;
void Main()
{
long typeHandle = typeof(Foo).TypeHandle.Value.ToInt64();
Console.WriteLine("addressOf(typeof(Foo)): 0x{0:x}", typeHandle);
MethodInfo instanceMethod1 = typeof(Foo).GetMethod("InstanceFunc1");
RuntimeHelpers.PrepareMethod(instanceMethod1.MethodHandle);
long addressOfInstanceMethod1 = instanceMethod1.MethodHandle.GetFunctionPointer().ToInt64();
Console.WriteLine("foo.InstanceFunc1: 0x{0:x}", addressOfInstanceMethod1);
MethodInfo instanceMethod2 = typeof(Foo).GetMethod("InstanceFunc2");
RuntimeHelpers.PrepareMethod(instanceMethod2.MethodHandle);
long addressOfInstanceMethod2 = instanceMethod2.MethodHandle.GetFunctionPointer().ToInt64();
Console.WriteLine("foo.InstanceFunc2: 0x{0:x}", addressOfInstanceMethod2);
MethodInfo staticMethod = typeof(Foo).GetMethod("StaticFunc");
RuntimeHelpers.PrepareMethod(staticMethod.MethodHandle);
long addressOfStaticMethod = staticMethod.MethodHandle.GetFunctionPointer().ToInt64();
Console.WriteLine("Foo.StaticFunc: 0x{0:x}", addressOfStaticMethod);
}
public class Foo
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static int StaticFunc() { return 1; }
[MethodImpl(MethodImplOptions.NoInlining)]
public int InstanceFunc1() { return 1; }
[MethodImpl(MethodImplOptions.NoInlining)]
public int InstanceFunc2() { return 1; }
}
关于c# - 在 C# 中获取 vtable 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14168090/