Get vtable address in c #?

I am ready to use unsafe . How can I get the address of a virtual table of a class and convert it to int?

+8
c #
source share
2 answers

(EDIT: Shoot - forgot that you must also make sure that it is not built-in - see edit)

You do not need to be unsafe, but you need to make sure that the JIT'ed method (that .PrepareMethod ):

Caution: I'm not entirely sure (without any additional research) how accurate these numbers are in the long run; I know that at some point they used to be exact, since I once used this to implement a swap runtime method ... shh

 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; } } 
+4
source share

Take a look at this article - this is for .NET 1.1, but this is the beginning. Since the internal structure of JIT is not very well documented, I'm not sure how much this applies to versions of the current version.

How the CLR creates runtime objects

This question may also be helpful.

+1
source share

All Articles