我在C中有一个压缩结构,我想在Python中解析.我注意到sizeof
C(使用GCC 4.9.2)和Python 3.4.2中的ctypes库之间的运算符返回的结构大小与位域的差异.
以下C代码按预期打印5:
#include <stdio.h>
#include <stdint.h>
typedef struct __attribute__((packed)) {
uint32_t ch0 : 20;
uint32_t ch1 : 20;
} pkt_t;
int main(){
printf("sizeof(pkt_t): %d\n", sizeof(pkt_t));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
虽然Python中的(相同)代码打印8
import ctypes
class Packet(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('ch0', ctypes.c_uint32, 20),
('ch1', ctypes.c_uint32, 20),
]
print(ctypes.sizeof(Packet()))
Run Code Online (Sandbox Code Playgroud)
看起来它_pack_ = 1
等同__attribute__((aligned(1)))
于C,而不是__attribute__((packed, aligned(1)))
使结构尽可能紧密地打包.有没有办法packed
为ctypes结构启用属性?