C ++到Delphi - 结构和指针添加

时间:2015-02-11 16:53:57

标签: c++ delphi struct

我在C ++中定义了这个宏;

    #define EXT_FIRST_EXTENT(__hdr__) \
((struct ext4_extent *) (((char *) (__hdr__)) +         \
                         sizeof(struct ext4_extent_header)))

ext4_extent_header是结构的地方;

    typedef struct ext4_extent_header {
    uint16_t  eh_magic;       /* probably will support different formats */
    uint16_t  eh_entries;     /* number of valid entries */
    uint16_t  eh_max;         /* capacity of store in entries */
    uint16_t  eh_depth;       /* has tree real underlying blocks? */
    uint32_t  eh_generation;  /* generation of the tree */
}__attribute__ ((__packed__)) EXT4_EXTENT_HEADER;

ext4_extent也是一个结构;

typedef struct ext4_extent {
    uint32_t ee_block; /* first logical block extent covers */
    uint16_t ee_len; /* number of blocks covered by extent */
    uint16_t ee_start_hi; /* high 16 bits of physical block */
    uint32_t ee_start_lo; /* low 32 bits of physical block */
} __attribute__ ((__packed__)) EXT4_EXTENT;

这是我尝试用Delphi写的;

function Ext2Partition.EXT_First_Extent(hdr: PExt4_extent_header):PExt4_ExtEnt;
begin
  Result := PExt4_ExtEnt(hdr + sizeof(ext4_extent_header));
end;

然而,编译器告诉我操作符不适用于此操作数类型。

这是我为ext4_extent_headerext4_extent转换为Delphi记录的c ++结构;

Type
  PExt4_extent_header = ^Ext4_extent_header;
  Ext4_extent_header = REcord
    eh_magic : Word;
    eh_entries : Word;
    eh_max : Word;
    eh_depth : Word;
    eh_generation : Cardinal;
  End;

Type
  PExt4_ExtEnt = ^Ext4_ExtEnt;
  Ext4_ExtEnt = Record
    ee_block : Cardinal;
    ee_len : Word;
    ee_start_hi : Word;
    ee_start_low : Cardinal;
  End;

谢谢!

2 个答案:

答案 0 :(得分:1)

以与C ++代码相同的方式投射hdr。它转换为指向八位字节的指针,以便指针算术将偏移量视为八位字节值。在德尔斐:

Result := PExt4_ExtEnt(PAnsiChar(hdr) + sizeof(ext4_extent_header));

您可以启用指针算法,使其更简单:

{$POINTERMATH ON}
....
Result := hdr + 1;

您的代码中可能存在其他问题。如果hdr确实是PExt4_ExtEnt,则C ++不需要宏。它可以写hdr + 1。所以我怀疑你需要深入研究C ++代码以找出hdr究竟是什么。


另请注意,C ++代码指定打包这些记录。在Delphi代码中使用packed record进行匹配。

答案 1 :(得分:1)

1)将您的功能更改为

function Ext2Partition.EXT_First_Extent(hdr: PExt4_extent_header):PExt4_ExtEnt;
begin
  Inc(hdr, 1); // It will increase _local copy_ of the hdr parameter to size of Ext4_extent_header, not to 1 byte. Keep in mind such behavior 
  Result := hdr;
end;

2)结果将在那之后指出? hdr之后的内容是什么?