计算结构大小而不填充字节的函数 [英] function that calculate Size of Structure without padding bytes

查看:35
本文介绍了计算结构大小而不填充字节的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个无需填充字节即可计算结构大小的函数.

Hi i want to make a function which calculate the size of structure without padding bytes.

示例:

struct test{
    int   x;
    char  y;
    int   z;
};

如果我计算上述结构的大小,我必须得到 9 个字节(即没有填充字节)

If i calculate the size of above structure i must get 9 byte (i.e. without padding bytes)

并考虑我可能不知道 struct 中存在的变量的情况.

And consider the case where i might not know the variable present in struct.

示例:

struct test{
    int   x;
    ....
    ....
    ....
    int   z;
};

所以如果我计算尺寸,它应该给出正确的尺寸.

so if i calculate the size it should give correct size.

是否可以编写这样的函数?我尝试阅读结构,但我找不到任何解决方案.我看到有一些编译器选项可以从中获得,但我不想要任何构建编译器选项.

Is it possible do write such function?I tried reading on structure's but i dint find any solution.I saw there is some compiler option are present from that i can get but i dont want any in build compiler option.

推荐答案

不,C 没有足够的内省来实现这一点.在运行时,程序没有任何信息可以用来了解"结构中的哪些字段,或者它们的类型.

No, C doesn't have enough introspection to make this possible. At run-time, there is no information left that the program can use to "know" which fields are in a structure, or what their types are.

这篇关于计算结构大小而不填充字节的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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