简体   繁体   中英

Copy multiple structs into a buffer using memcpy in c

  1. I have several structs (of u8 fields) which I want to convert into a buffer, is this the best way?

     struct struct_a a; struct struct_b b; u8 buffer[64]; u8 *next_pos; os_memcpy(buffer, &a, sizeof(struct_a)); next_pos = buffer + sizeof(struct_a)/sizeof(u8); os_memcpy(next_pos, &b, sizeof(struct_b)); 
  2. Is this the best way to calculate the overall length of the buffer?

     buffer_len = (sizeof(struct_a) + sizeof(struct_b) + ... )/sizeof(u8); 

Thanks

I assume that u8 means unsigned 8 bits. Hence, sizeof(u8) equals 1. So you can simply write:

os_memcpy(&buffer[sizeof(struct_a)], &b, sizeof(struct_b));

For your second question, except that dividing by 1 is useless, it's a perfectly fine way to compute the len of the buffer.

I'm not a big fan of buffer + sizeof(struct_a) but it's also good.

Edit: Also, when doing that kind of stuff, if the size of the elements of buffer is not 1, I cast buffer into something with your equivalent of u8 . This way, I don't have to divide by the size of the elements of buffer.

Define a buffer either this way,

#define MAXBUF (999)
type struct 
{
    int size; //or short, or char, or long long, depending on size...
    char buffer[MAXBUF];
} buffer_t;

Or, this way, and allocate enough space (enough defined to be how much you need),

#define MAXBUF (999)
type struct 
{
    int size;
    char buffer[MAXBUF];
} buffer_t;

Then a function to add stuff to the buffer,

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);
}

Now, using it is easy,

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM