以这种方式定义缓冲区,
#define MAXBUF (999)
type struct
{
int size; //or short, or char, or long long, depending on size...
char buffer[MAXBUF];
} buffer_t;
或者,通过这种方式,并分配足够的空间(足够定义为您需要多少),
#define MAXBUF (999)
type struct
{
int size;
char buffer[MAXBUF];
} buffer_t;
然后是一个向缓冲区添加东西的函数,
int
buffer_add(buffer_t* buffer,void* thing,int len)
{
if(!thing) return 0;
if(len<1) return 0;
memcpy( &(buffer[buffer->size]),thing,len);
return(buffer->size+=len);
}
现在,使用它很容易,
typedef char u8;
struct struct_a { u8 x[100]; };
struct struct_b { int y[25]; };
int main()
{
u8 buffer[64];
u8 *next_pos;
buffer_t mybuffer;
buffer_add(&mybuffer,&a,sizeof(a));
buffer_add(&mybuffer,&b,sizeof(b));
buffer_add(&mybuffer,&buffer,sizeof(buffer));
buffer_add(&mybuffer,next_pos,sizeof(*next_pos));
//do stuff with mybuffer
}