像C++这样的Delphi模板

Delphi Templates like C++?

本文关键字:Delphi 模板 C++      更新时间:2023-10-16

有人能帮我转换这段代码吗?

我对C++不太了解,所以我需要将这段代码从C++转换为delphi:

template <typename DestType, typename SrcType>
DestType* ByteOffset(SrcType* ptr, ptrdiff_t offset)
{
        return reinterpret_cast<DestType*>(reinterpret_cast<unsigned char*>(ptr) + offset);
}

谢谢。。。

转换起来其实很简单,但不能在Delphi中使用模板。它只是向指针添加偏移量,但偏移量是以字节而不是指针基类型的倍数指定的。

所以转换

ByteOffset<IMAGE_NT_HEADERS>(DosHeader, DosHeader->e_lfanew)

进入

PIMAGE_NT_HEADERS(PAnsiChar(DosHeader)+DosHeader.e_lfanew)

更多示例:

ExportDirectory := PIMAGE_EXPORT_DIRECTORY(PAnsiChar(DosHeader)+
    NtHeader.OptionalHeader.
    DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
functions := PDWORD(PAnsiChar(DosHeader)+ExportDirectory->AddressOfFunctions);

等等。

Delphi Generics是最接近C++模板的等价物,例如:

type
  ByteOffset<DestType, SrcType> = class
  public
    type
      PSrcType = ^SrcType;
      PDestType = ^DestType;
    class function At(ptr: PSrcType; offset: NativeInt): PDestType;
  end;
class function ByteOffset<DestType, SrcType>.At(ptr: PSrcType; offset: NativeInt): PDestType;
begin
  Result := PDestType(PByte(ptr) + offset);
end;

var
  I: Integer;
  W: PWord;
begin
  I := $11223344;
  W := ByteOffset<Word, Integer>.At(@I, 2);
end;