Re: [问题] struct alignment

楼主: BaJiaJhon (BaJiaJhon)   2019-12-19 04:05:08
既然是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;
}

Links booklink

Contact Us: admin [ a t ] ucptt.com