【问题标题】:How do I convert a C union to delphi?如何将 C union 转换为 delphi?
【发布时间】:2019-02-10 04:20:10
【问题描述】:

我正在将 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 name 但是原始的c代码是无名的。 如何将 C 中的匿名联合或结构转换为 Delphi?

【问题讨论】:

    标签: c delphi


    【解决方案1】:

    你所拥有的还不错,但在我的文章 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;
    

    也可以将它添加到相同大小的SingleInt32 分支中,而不是在UInt32 分支中。这仍然会导致与 C 中的结构相同的内存布局,&type 在偏移量 4 处,记录的大小为 5,这就是全部。只需看一下文章中的图表即可进行澄清:

    这样,没有必要给联合部分自己的类型和自己的名字。如果您不相信“技巧”,请使用 code I give in the same article 检查 C 和 Delphi 中的偏移量。

    Borland 和 Embarcadero 以及 Delphi-JEDI 使用 (d) 相同的技巧来转换匿名联合,并且构建了 Delphi TVarRec(用于 array of const 参数)和 TVarType(用于变体)记录也是。

    【讨论】:

    • 谢谢!我对您的代码有 1 个问题。为什么使用指针 param_union_p 和 PParamUnion?我想教它,因为我缺乏经验。 :)
    • 我已经转换了许多 API 头文件,并且声明指针类型和漂亮的(类似 Delphi 的)名称总是有意义的,即没有 un_der_scores 和 CamelCapped。 C 和 C++ 中的 _t 后缀通常与 Delphi 中的 T 前缀具有相同的含义,因此对于指针,我使用了 _p 后缀,而在 Delphi 中将使用 P 前缀。 PSomething = ^TSomething; 这样的行在此类翻译中很常见。
    猜你喜欢
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多