首页 文章

C到Delphi - 结构和指针添加

提问于
浏览
1

我在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;

但编译器告诉我,运算符不适用于此操作数类型 .

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

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 回答

  • 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)将您的功能更改为

    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 之后的内容是什么?

相关问题