【问题标题】:Delphi Templates like C++?像 C++ 这样的 Delphi 模板?
【发布时间】:2012-02-28 12:37:58
【问题描述】:

请问,谁能帮我转换一下这段代码?

我对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 没有模板,无法直接转换代码。要继续,我们需要查看代码是如何使用的。
  • @DavidHeffernan,此函数中使用此代码:pastebin.com/7d9N1J2c"eat_hook"
  • 虽然这看起来很复杂,但这个函数只是为指针添加了一个偏移量,与指针类型无关。
  • @ereOn,在delphi中怎么样?谢谢

标签: c++ delphi templates pascal


【解决方案1】:

转换其实很简单,但是你不能在 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);

等等。

【讨论】:

  • 现在,你能帮我处理这些代码吗? PIMAGE_EXPORT_DIRECTORY ExportDirectory = ByteOffset(DosHeader, ` NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);` 和DWORD* functions = ByteOffset&lt;DWORD&gt;(DosHeader, ExportDirectory-&gt;AddressOfFunctions);
  • 使用完全相同的模式。第一步是了解 C++ 代码的作用,以及为什么 Pascal 代码是等价的。我(或其他人)可以为你做这一切,但那样你就什么也学不到了。我相信你可以做到这一点!
  • 大卫,我想我知道我转换了代码..你能看看它是否正确吗? ` ExportDirectory := PImageExportDirectory(DWORD(DOSHeader) + DWORD(NTHeaders^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress));函数 := DWORD(DWORD(DOSHeader) + DWORD(ExportDirectory^.AddressOfFunctions));`
  • 如果你在 64 位编译时会失败,因为你会截断指针。我会在答案中添加更多内容。
  • 好的,我将终止转换并测试它。非常感谢大卫! s2
【解决方案2】:

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;

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 2020-12-18
    • 2022-07-14
    • 2012-08-16
    相关资源
    最近更新 更多