How does `__declspec (align (#)) work?

Yes : http://msdn.microsoft.com/en-us/library/83ythb65.aspx But this is not clear to me. First of all, __declspec(align(#)) makes each object (in the structure) declared with it begin with a aligned offset. This part is clear. Aligment is also “inherited” by a structured object. But it does not resize the object, does it? This is why sizeof() in this code:

 __declspec(align(32)) struct aType {int a; int b;}; sizeof(aType); 

return 32 ?

+6
source share
2 answers

The size of an object is used to calculate offsets in arrays and when using pointers, so sizeof(x) should always be a multiple of the alignment value. In this case, 1 x 32. But if you have __declspec(align(32)) struct aType {int a[12]; }; __declspec(align(32)) struct aType {int a[12]; }; , then the size will be 2 x 32 = 64, since sizeof (a) is 12 x 4 = 48. If we change it to align to 4, 8 or 16, it will be 48.

The way it actually works is for the compiler to add an unnamed padding element after named structure elements to fill the structure to the alignment size.

If this does not work, then it’s like:

  aType *aPtr = new aType[15]; aPtr[12].a = 42; 

will not work correctly as the compiler will multiply 12 by sizeof(aPtr) to add to aPtr internally.

+12
source

The documentation is either poorly written, or my team of English as a foreign language does not match it.

 // make a nice 16 align macro #ifndef ALIGN16 #define ALIGN16 __declspec(align(16)) #endif // align the structure struct ALIGN16 CB { ALIGN16 bool m1; // and ALIGN16 int m2; // align ALIGN16 int m3; // each ALIGN16 short m4; // element }; // now it performs as expected printf("sizeof(CB) %d\r\n", sizeof(CB)); CB vCb; printf("CB: %p, %%%d\r\n", &vCb, (UINT_PTR)&vCb % 16); printf("CB.m1: %p, %%%d\r\n", &vCb.m1, (UINT_PTR)&vCb.m1 % 16); printf("CB.m2: %p, %%%d\r\n", &vCb.m2, (UINT_PTR)&vCb.m2 % 16); printf("CB.m3: %p, %%%d\r\n", &vCb.m3, (UINT_PTR)&vCb.m3 % 16); printf("CB.m4: %p, %%%d\r\n", &vCb.m4, (UINT_PTR)&vCb.m4 % 16); 

__declspec(align(#)) affects only the alignment of the structure and sizeof() , and not each of the members in it. If you want each property to be aligned, you need to specify alignment at the member level.

I also initially assumed that a struct-level __declspec(align()) affects it and its members, but it is not. Therefore, if you want each member to be aligned, you need to be specific.

0
source

Source: https://habr.com/ru/post/951464/


All Articles