作者BaJiaJhon (BaJiaJhon)
看板C_and_CPP
标题Re: [问题] struct alignment
时间Thu Dec 19 04:05:08 2019
既然是C、又是MCU,直接对齐後,
用指标位移去存取应该是比较合理的
解法。
效能跟花费空间应该足够小了。但牺
牲的就是可读性,跟扩充性,也不适
合暴露在太多地方,小范围使用还是
OK的。
如果位移不一样,而且有其他地方可
以知道物件种类的话,可以建立位移
表来查询该结构的位移。
另外不同编译器,对齐的方式以及
attribute可能会不同。手边刚好没有
硬体可以测试,在windows上结果是
OK的,编译器是MinGW-W64。
希望能钓出更多高手来回文。
gist 好读版
https://reurl.cc/D1pZRO
#include <inttypes.h>
#include <stdio.h>
typedef struct __attribute__((packed, aligned(1))) _A
{
uint8_t num;
uint16_t a;
} A_t;
typedef struct __attribute__((packed, aligned(1))) _B
{
uint8_t num;
uint32_t b;
} B_t;
void num_plus_plus(void *p){
*((uint8_t*)(p + 0)) += 1;
}
int main(int argc, char const *argv[])
{
A_t a = {
.num = 0,
.a = 0
};
B_t b = {
.num = 3,
.b = 1
};
printf("a.num = %d, b.num = %d\n", a.num, b.num);
num_plus_plus(&a);
printf("a.num = %d, b.num = %d\n", a.num, b.num);
num_plus_plus(&b);
printf("a.num = %d, b.num = %d\n", a.num, b.num);
return 0;
}
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.231.155.188 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1576699511.A.C94.html
※ 编辑: BaJiaJhon (49.216.43.113 台湾), 12/19/2019 04:08:54