Sign in to follow this  
David Neubelt

Aligning structure members

Recommended Posts

Hey, I need to align structure members to 16 byte boundaries. I tried struct Foo { __declspec(align(16)) volatile unsigned int* data0; __declspec(align(16)) volatile unsigned int* data1; __declspec(align(16)) volatile unsigned int* data2; __declspec(align(16)) volatile unsigned int* data3; }; Though, the members were aligned to 8 byte boundaries. I was thinking of doing this __declspec(align(16)) struct Foo { volatile unsigned int* data0; uint32 padding0; uint32 padding1; volatile unsigned int* data1; uint32 padding2; uint32 padding3; }; Though, that assumes pointers are 8 bytes so I'd have to make defines to determine how much padding are between each variable per platform. Any other ideas? I'm only having this problem with visual studio not other compilers :( -= Dave

Share this post


Link to post
Share on other sites
Strange. Under MVC2008:
struct Foo {
__declspec( align( 16 ) ) volatile unsigned int* data0;
__declspec( align( 16 ) ) volatile unsigned int* data1;
__declspec( align( 16 ) ) volatile unsigned int* data2;
__declspec( align( 16 ) ) volatile unsigned int* data3;
};

int main()
{
Foo foo;
printf("%d %d\n", sizeof(Foo), sizeof(foo));
printf("%x %d\n", &foo.data0, offsetof(Foo, data0));
printf("%x %d\n", &foo.data1, offsetof(Foo, data1));
printf("%x %d\n", &foo.data2, offsetof(Foo, data2));
printf("%x %d\n", &foo.data3, offsetof(Foo, data3));
return 0;
}
results in:
64 64
12ff30 0
12ff40 16
12ff50 32
12ff60 48


That failing to work, there's always the possibility of using a union. Perhaps:
struct DataPtr {
union {
volatile int * data;
char padding[16];
} value;
volatile int * operator->() { return value.data; }
volatile int * operator*() { return value.data; }
};

struct Foo2 {
DataPtr data0;
DataPtr data1;
DataPtr data2;
DataPtr data3;
};
Granted, it's a bit messy.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this