c++templatesdelphi

Delphi templates like in C++?


I need to convert this code from C++ to Delphi:

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

Solution

  • It's actually pretty simple to convert, but you can't use templates in Delphi. It is merely adding an offset to a pointer, but the offset is specified in bytes rather than multiples of the pointer base type.

    So convert

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

    into

    PIMAGE_NT_HEADERS(PAnsiChar(DosHeader)+DosHeader.e_lfanew)
    

    Some more examples:

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

    and so on.