我正在将C库转换为Delphi. 我在转换下面的代码时遇到问题. 这是用于通信的结构,因此顺序必须正确. 德尔福 Tparam_union_params_t = packed record case Integer of 0: (param_float:single); 1: (param_int32:Int3
我在转换下面的代码时遇到问题.
这是用于通信的结构,因此顺序必须正确.
德尔福
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?
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,这就是所有重要的.请查看文章中的图表以获得澄清:
这样,就不需要为union部分提供自己的类型和自己的名称.如果您不相信“技巧”,请使用code I give in the same article检查C和Delphi中的偏移量.
Borland和Embarcadero以及Delphi-JEDI使用(d)同样的技巧来翻译匿名联合,Delphi TVarRec(用于const参数数组)和TVarType(用于Variants)记录也是这样构建的.
