【发布时间】:2017-05-10 05:32:21
【问题描述】:
我正在使用打包结构通过直接 DMA 访问进行通信,这是我的测试代码:
// structure for communication buf 1
typedef __packed struct _test1
{
uint8_t a;
uint32_t b;
uint16_t c;
uint16_t d;
uint32_t e;
} test1;
// structure for communication buf 2
.
.
.
// structure for communication buf 3
.
.
.
// structure for communication buf set
typedef __packed struct _test2
{
uint8_t dump[3];
test1 t;
// may have many other packed structure for communication buf
} test2;
#pragma anon_unions
typedef struct _test3
{
union
{
uint32_t buf[4];
__packed struct
{
__packed uint8_t dump[3];
test1 t;
};
};
} test3;
test1 t1;
test2 t2;
test3 t3;
这些结构的大小是
sizeof(t1) = 13
sizeof(t2) = 16
sizeof(t3) = 16
如果我想访问变量 b,为了不影响性能,需要对齐访问的读/写内存内容,并手动计算偏移量
t3.buf[1]
但如果不使用未对齐访问,我无法在结构中读取/写入变量
t2.t.b
t3.t.b
所以我定义了类似下面代码的结构,只打包变量a
typedef struct _test4
{
__packed uint8_t a;
uint32_t b;
uint16_t c;
uint16_t d;
uint32_t e;
} test4;
typedef struct _test5
{
__packed uint8_t dump[3];
test4 t;
} test5;
test4 t4;
test5 t5;
虽然结构中所有元素的访问都是对齐的,但是填充也是插入的
sizeof(t4) = 16
sizeof(t5) = 20
那么我如何定义打包结构,并在不使用未对齐访问(a 除外)的情况下访问其中的单个变量?
非常感谢您的帮助
【问题讨论】:
-
打包取决于供应商 - 您使用的是哪个编译器/操作系统/芯片组
-
keil arm编译器v5.06/无嵌入式操作系统/freescale kv系列
-
即使在从某个地方接收到的结构化数据上覆盖 C
structs看起来很诱人,但它通常会导致比它解决的问题更多的问题,而且通常不是一个好主意。将字节接收到一个普通的字节缓冲区并从那里构建你的结构。 -
它是一个封闭的环境,接收时无需担心重建结构,但是要传输/保存的数据太多,我需要减少我的结构大小以防万一尽可能影响性能
标签: c struct structure padding packing