Search code examples
c#.netunmanagedvtable

Call unmanaged function in struct from VTable


Is it possible to call functions from C#, to an unmanaged function in a struct (via VTable).

For example, I am in-process hooking an application, and I am re-creating the structs for each class (of the application).

public struct SomeStruct {
   [FieldOffset(0x00)]
   public IntPtr * VTable;

   [FieldOffset(0x10)]
   public uint SomeValue;
}

Then, I usually do:

var * data = (SomeStruct*)(Address);

And I wish to call a function from the VTable of the structure in either of the following ways

Invoke<delegate>(data->VTable[0x3C])(delegateArguments)

Or

var eax = Invoke<Func<uint,uint>(data->VTable[0x3C])(arg1,arg2)

Furthermore, could this be done efficiently (as these vtable funcs could be called numerous times)?

Perhaps via Reflection Emit?

From what I know, marshalling has to create the delegate function every time I call the Invoke<> func.


Solution

  • Given that a virtual method table contains pointers to functions, assuming you know the offset (which it appears you do) you can get the pointer value in an IntPtr by calling the ReadIntPtr method on the Marshal class, like so:

    IntPtr ptr = Marshal.ReadIntPtr(data.VTable, 0x3C);
    

    Then you can call the GetDelegateForFunctionPointer method on the Marshal class to get a delegate of the appropriate type, like so:

    // Assuming a signature of f(int, int) returning int
    Func<int, int, int> func = (Func<int, int, int>)
        Marshal.GetDelegateForFunctionPointer(ptr, typeof(Func<int, int, int>));
    

    Then you can call the delegate as needed.