像C++这样的Delphi模板
Delphi Templates like C++?
有人能帮我转换这段代码吗?
我对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;
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中为模板函数实例创建快捷方式
- 使用C++中的模板和运算符重载执行矩阵运算
- 有人能分解一下这个c++模板的语法吗
- 如何在c++17中制作一个模板包装器/装饰器
- 模板化建造师专业化
- 调用专用模板时出错"no matching function for call to [...]"
- 模板元程序查找相似的连续类型名称
- 如何在C++20中创建模板别名的推导指南
- 没有名称的C++模板参数
- 具有重复类型的C++可变模板
- 如何将enable-if与模板参数和参数包一起使用
- 像C++这样的Delphi模板