Delphi pointer casting

c, casting, delphi, pointers

Solution

This is not a 100% translation of the C code but it does what you are trying to achieve by using this method:

  function GetInterfaceMethod(const intf; methodIndex: Cardinal): Pointer;
  type
    PPVtable = ^PVtable;
    PVtable = ^TVtable;
    TVtable = array[0..MaxInt div SizeOf(Pointer) - 1] of Pointer;
  begin
    Result := PPVtable(intf)^^[methodIndex];
  end;

This code illustrates the fact that an interface reference is a pointer to the IMT as shown below:

Problem

I want to use this simple C function in delphi, but cant cast the values to pointer perfectly. C function : ``` PVOID GetInterfaceMethod(PVOID intf, DWORD methodIndex) { return *(PVOID*)(*(DWORD_PTR*)intf + methodIndex); } ``` Delphi function : ``` function GetInterfaceMethod(const intf; methodIndex: DWORD): Pointer; begin // return *(PVOID*)(*(DWORD_PTR*)intf + methodIndex); x64 // return *(PVOID*)(*(DWORD*)intf + methodIndex * 4); x86 Result := Pointer(Pointer(DWORD_PTR(Pointer(intf)^) + methodIndex)^); //x64 end; ``` Excuse me for my bad English.

Original source