c - 如何将 C union 转换为 delphi?

标签 c delphi

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

我的方法需要变量名 但原始的 C 代码没有命名。 如何将 C 中的匿名 union 或结构转换为 Delphi?

最佳答案

你有的还不错,但是在我的文章里Pitfalls of converting我描述了一种稍微好一点的技术来处理这种没有名字的 union :

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,这就是最重要的。只需看一下文章中的图表即可进行说明:

enter image description here

这样,就不需要给 union 部分自己的类型和名字了。如果您不相信这个“​​把戏”,请使用 code I give in the same article检查 C 和 Delphi 中的偏移量。

Borland 和 Embarcadero,还有 Delphi-JEDI,使用 (d) 相同的技巧来翻译匿名 union ,以及 Delphi TVarRec(用于 array of const parameters)和 TVarType(对于 Variants)记录也是以这种方式构建的。

关于c - 如何将 C union 转换为 delphi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54613312/

相关文章:

regex - 如何使用 RegEx 获取 Ini 文件中的节名称

c - LLVM:为什么在构建调用时会出现段错误?

c - 使用 glib 通过 DBus 发送包含数组的结构数组

c - C 中的引用计数和函数内部分配的内存

delphi - Delphi中的类字段(静态字段)

arrays - Delphi 中常量数组的常量集

delphi - 如何获取动态数组的内存大小?

c - 使用零流优化更新 MD5/SHA1

c - 如何从打开的 cv 中的文件夹中读取多个图像(使用 C)

delphi - 简单的 OpenGL 代码不起作用