简体   繁体   English

在C中使用memcpy将多个结构复制到缓冲区中

[英]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? 我有几个要转换为缓冲区的(u8字段)结构,这是最好的方法吗?

     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. 我假设u8表示无符号的8位。 Hence, sizeof(u8) equals 1. So you can simply write: 因此, sizeof(u8)等于1。因此,您可以简单地编写:

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. 对于您的第二个问题,除以1除无用外,这是计算缓冲区的len的绝佳方法。

I'm not a big fan of buffer + sizeof(struct_a) but it's also good. 我不是buffer + sizeof(struct_a)但也很好。

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 . 编辑:此外,当做这种事情时,如果buffer的元素大小不为1,我会将buffer转换为与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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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