c到delphi结构的转换

时间:2010-11-13 08:43:50

标签: c++ c delphi

有人可以告诉我从c到delphi的谈话是否正常:

c code

struct nfq_data {
    /* packet_hdr - it HAVE to be the same as struct nfqnl_msg_packet_hdr */
    struct {
        uint32_t packet_id; /* unique ID of packet in queue in network order */
        uint16_t hw_protocol; /* hw protocol in network order */
        uint8_t hook; /* netfilter hook */
    } packet_hdr;
    /* packet_hw - it HAVE to be the same as struct nfqnl_msg_packet_hw */
    struct {
        uint16_t hw_addrlen; /* len of hw_addr in network order */
        uint16_t _pad;
        uint8_t hw_addr[8];
    } packet_hw;
    /* tm */
    struct {
        long sec;
        long usec;
    } tm;

    uint32_t if_index; /* Unique iface id */
    uint32_t verdict; /* Netfilter verdict value */
    uint32_t mark; /* Mark value */
    uint8_t if_name[IFNAMSIZE]; /* Name of incoming or outgoing iface */
    uint32_t data_len; /* Length of packet */
    uint8_t payload[0]; /* packet data */
};

,其中

typedef unsigned char uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;

delphi

_packet_hdr = record
    packet_id: Cardinal;
    hw_protocol: Word;
    hook: Byte;
  end;

  _packet_hw = record
    hw_addrlen: Word;
    _pad: Word;
    hw_addr: array[0..7] of byte;
  end;

  _tm = record
    sec: Int64;
    usec: Int64;
  end;

  pnfq_data = ^nfq_data;
  nfq_data = record
    packet_hdr: _packet_hdr;
    packet_hw: _packet_hw;
    tm: _tm;
    if_index: Cardinal;
    verdict: Cardinal;
    mark: Cardinal;
    if_name: array[0..254] of Byte;
    data_len: Cardinal;
    payload: PChar; //TBytes;
  end;

    packet_hdr: _packet_hdr;
    packet_hw: _packet_hw;

我收到的很好,但在那之后没什么好。

提前致谢

3 个答案:

答案 0 :(得分:1)

uint8_t payload[0];

这真的是一个指针(如你的delphi代码中)或一个大小为0的inplace数组,用于表示标题之后的数据

您应将记录标记为packed我认为这不会对你的具体代码产生影响,但这是一种很好的做法,因为包装规则很容易出错,可能会改变而不是每个人都知道它们。
它可能有所不同,因为packet_hdr在打包时大7字节大,所以后面的packet_hw在打包时从偏移量7开始,并且在对齐时可能是8。

答案 1 :(得分:0)

我认为你需要用#pragma pack(push,1) / #pragma pack(pop)包围你的结构(如果我们讨论的是Visual Studio)。

答案 2 :(得分:0)

根据您的评论 “我收到的很好,但在那之后没什么好。”

我假设您从“C”应用程序获取数据 -

在“delphi编译器”代码生成选项屏幕中查看“记录字段别名” 有许多不同的选项,例如“四字”或“字”对齐。