在GNUC可变长度结构 [英] variable length struct in gnuc

查看:113
本文介绍了在GNUC可变长度结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是能够GNUC定义一个可变长度的结构重新present一个对象如下:

Is it able to define a variable length struct in gnuc to represent a object as follow:

field1: fixed 4bytes;
field2: length of field3
field3: variable length
field4: length of field5
field5: variable length
field6: fixed 8bytes
field7: fixed 1byte

我知道GNUC我们可以使用零大小的数组实现一个可变长度的结构,例如

I know in gnuc we can use the zero-size array to implement a variable length struct, e.g.

typedef struct varStruct{
  int foo1;
  int foo2[0];
}varStruct;

但上面的使用需要放置在该结构的尾可变长度字段。
如果他们是在什么中间?

But the above usage requires the variable length field placed at the tail of the struct. What if they are in the middle?

推荐答案

您不能有多个变量数组或在中间变量数组的结构体。想想吧,怎么会编译器知道在哪里 FIELD3 字段4 开始,如果长度字段2 是变量?

You can't have a struct with more than one variable array or a variable array in the middle. Think about it, how would the compiler know where field3 and field4 start if the length field2 is variable?

如果字段1 包含下面的两个字段的长度,你可以手动读取结构的成员。例如:code(它读成伪code):

If field1 contains the length of the next two fields, you could read the members of the struct manually. Example code (read it as pseudocode):

#define PADDING 8 /* or perhaps sizeof(void *) */

typedef struct {
   int32_t field_len;
   char data[0];
} main_str_t;

typedef struct {
   int64_t one;
   int8_t another;
} tail_str_t;

....

main_str_t *data = get_data();
int32_t len = data->field_len;
int32_t padded_len = ((field_len + PADDING - 1) / PADDING) * PADDING;
char *field2 = data->data;
char *field3 = field2 + padded_len;
tail_str_t *tail = field3 + padded_len;

这篇关于在GNUC可变长度结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆