Reputation: 586
Please, can anyone convert this code for me?
I don't know so much about C++, so 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);
}
Thank you...
Upvotes: 2
Views: 4411
Reputation: 596101
Delphi Generics is the closest equivilent to C++ templates, eg:
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;
Upvotes: 3
Reputation: 612954
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.
Upvotes: 4