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