如何确保一个成员是4字节对齐? [英] How to ensure a member is 4-byte aligned?

查看:945
本文介绍了如何确保一个成员是4字节对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使用OSAtomicDecrement(mac特定的原子操作),我需要提供一个4字节对齐的SInt32。

In order to use OSAtomicDecrement (mac-specific atomic operation), I need to provide a 4-byte aligned SInt32.

这种烹饪工作吗?是否有其他方法来处理对齐问题?

Does this kind of cooking work ? Is there another way to deal with alignment issues ?

struct SomeClass {
  SomeClass() {
    member_  = &storage_ + ((4 - (&storage_ % 4)) % 4);
    *member_ = 0;
  }

  SInt32 *member_;

  struct {
    SInt32 a;
    SInt32 b;
  } storage_;
};


推荐答案

如果您使用Mac, 。 GCC可以为您自动调整变量:

If you're on a Mac, that means GCC. GCC can auto align variables for you:

  __attribute__((__aligned__(4))) int32_t member_;

请注意,这不能在编译器中移植,因为这是GCC特定的。

Please note that this is not portable across compilers, as this is GCC specific.

这篇关于如何确保一个成员是4字节对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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