在我的网络应用程序中,我想使用一个偏移量作为指向已知结构的指针,而不是使用memcpy() 2次(rx/tx)复制结构的每个字段太重了。我知道我的gcc 4.7.2(选项:-O3)在cortex-a8上可以使用1条指令不对齐地执行memcpy(&a,&buff,4),因此它可以访问未对齐的int。假设它可能有很多结构或大结构,最好的方法是什么?
struct __attribute__ ((__packed__)) msg_struct {
int a; //0 offset
char b; //4 offset
int c; //5 offset
int d[100]; //9 offset
}
char buff[1000];// [0]:header_size [1-header_size]:header [header_size+1]msg_struct
func() {
struct msg_struct *msg;
recv ((void *)buff, sizeof(buff));
msg=buff+header_size; // so, it is unaligned.
...
// some work like:
int valueRcv=msg->c;
//or modify buff before send
msg->c=12;
send(buff,sizeof(buff));
}
buff
是一个int
数组吗?添加header_size
会使你的指针指向一个非常错误的位置。 - Sergey Kalinichenko