加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将C联合转换为delphi?

发布时间:2020-12-16 09:22:50 所属栏目:百科 来源:网络整理
导读:我正在将C库转换为Delphi. 我在转换下面的代码时遇到问题. 这是用于通信的结构,因此顺序必须正确. 德尔福 Tparam_union_params_t = packed record case Integer of 0: (param_float:single); 1: (param_int32:Int32); 2: (param_uint32:UInt32); ... ...end;
我正在将C库转换为Delphi.
我在转换下面的代码时遇到问题.
这是用于通信的结构,因此顺序必须正确.

德尔福

Tparam_union_params_t = packed record
  case Integer of
    0: (param_float:single);
    1: (param_int32:Int32);
    2: (param_uint32:UInt32);
    ...
    ...
end;

Tparam_union_t = packed record
  param:Tparam_union_params_t // This method requires var name.
  type:UInt8;
end;

C郎

#ifdef __GNUC__
  #define PACKED( __Declaration__ ) __Declaration__ __attribute__((packed))
#else
  #define PACKED( __Declaration__ ) __pragma( pack(push,1) ) __Declaration__ __pragma( pack(pop) )
#endif

PACKED(
typedef struct param_union {
    union {
        float param_float;
        int32_t param_int32;
        uint32_t param_uint32;
        int16_t param_int16;
        uint16_t param_uint16;
        int8_t param_int8;
        uint8_t param_uint8;
        uint8_t bytes[4];
    }; // This no-named union. no-named is important.
    uint8_t type;
}) param_union_t;

我的方法需要var名称
但原始的c代码没有命名.
如何将C中的匿名联合或结构转换为Delphi?

解决方法

你有什么不错,但在我的文章 Pitfalls of converting中,我描述了一种稍微更好的技术来处理这样一个没有名字的联盟:

param_union_p = ^param_union_t;
param_union_t = packed record
  case Integer of
    0: (param_float: Single);
    1: (param_int32: Int32);
    2: (param_uint32: UInt32;    // add the members after the union to the largest branch.
        &type: UInt8);
    3: (param_int16: Int16);
    ...
    ...
end;
PParamUnion = ^TParamUnion;
TParamUnion = param_union_t;

它也可以添加到相同大小的Single或Int32分支中,而不是在UInt32分支中.这仍将导致与C中的结构相同的内存布局,其中& type位于偏移4处,并且记录的大小为5,这就是所有重要的.请查看文章中的图表以获得澄清:

enter image description here

这样,就不需要为union部分提供自己的类型和自己的名称.如果您不相信“技巧”,请使用code I give in the same article检查C和Delphi中的偏移量.

Borland和Embarcadero以及Delphi-JEDI使用(d)同样的技巧来翻译匿名联合,Delphi TVarRec(用于const参数数组)和TVarType(用于Variants)记录也是这样构建的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读