方法自动字段类似C结构重新排序 [英] Approach for automatic fields reordering in C-like structs

查看:214
本文介绍了方法自动字段类似C结构重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来执行<一个href="http://stackoverflow.com/questions/9486364/why-cant-c-compilers-rearrange-struct-members-to-eliminate-alignment-padding">automatic场在C-状结构重新排序?我的意思是使用类似(preprocessor的C和C ++和模板/类型特征的/ etc C ++),这使得它可以做到下面的宏(Boost.Fusion般的风格,以适应结构)的语言特征:

Is there a way to perform automatic fields reordering in C-like structs? I mean the using of the language features like( preprocessor for C and C++ and templates/type traits/etc for C++), which make it possible to do the following macro (Boost.Fusion-like style to adapt structures):

REARRANGE(StructureName,
          (int8_t)(FieldName1),
          (int32_t)(FieldName2),
          (int16_t)(FieldName3),
          (int32_t)(FieldName4));
// is equivalent to (without loss of generality):
struct StructureName
{

    int32_t FieldName2;
    int32_t FieldName4;
    int16_t FieldName3;
    int8_t FieldName1;

};

当然,办法应考虑到 alignof 值(连同的sizeof )的领域,如果它可能的话,的#pragma包当前值。

Of course, approach should take into account alignof values (together with sizeof) for fields and, if it possible, #pragma pack current value.

我知道不好结果的便携性,但是它对于本地使用。

I am aware of bad portability of the result, but it for local use only.

这是强制性的东西保存的字段名称以及各自的类型。

It is mandatory thing to save the field names together with respective types.

其目的是降低总结构尺寸

The aim is to reduce total structure size.

推荐答案

  • For MS compiler use #pragma pack, (#pragma pack(1) eliminates all gaps). And check the link for details, as this directive is not guaranteed to work always.
  • For GCC there is __attribute__ ((packed))
  • 作为你唯一的目标就是在内存中的数据的最小可能的大小,这正是你需要的。

    As your only goal is the minimal possible size of the data in memory, this is exactly what you need.

    这篇关于方法自动字段类似C结构重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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