views:

710

answers:

2

Hi,

I have a 32-bit .NET assembly which PInvokes into the C layer. I want to port this assembly to 64-bit. I have read many documents related to porting to 64-bit, all of which seems to suggest that we need to take care of the alignment if we are to use structures.

I had a general question related to structure alignment and wanted to clarify that first so that I dont miss anything.

Suppose I have a C entry point which accepts a struct pointer and basically fills up the values inside. This C code does not have any packing directives and I have all the .NET structs aligned to pack=8. So if I pass a structure with adjacent ints, I thought it could be a problem interpreting the data populated in the .NET layer, as the C by default would use pack=4 and we are interpreting the struct as pack=8 in .NET layer, so thought it could cause a problem. But it doesn't seem to be the case. The data seems to be interpreted fine.

Can anyone explain this behavior?

Thanks, Niranjan

A: 

I came across this msdn article http://msdn.microsoft.com/en-us/library/aa366769(VS.85).aspx

It suggests that specifying a packing level larger than the natural alignment of a type does not change the type alignment. So since the natural alignment in the above case I mentioned is 4, setting the packing to 8 does not really change the alignment of the structure. This explains the behavior.

Niranjan U
A: 

By default, members of a structure or union are aligned on their natural boundaries; one byte for a char, two bytes for a short, four bytes for an integer etc. If n is present, it must be a power of 2 specifying the strictest natural alignment for any structure or union member.

For example, #pragma pack(2) aligns int, long, long long, float, double, long double, and pointers on two byte boundaries instead of their natural alignment boundaries. If n is the same or greater than the strictest alignment on your platform, (four on x86, eight on SPARC v8, and 16 on SPARC v9), the directive has the effect of natural alignment.

I'm not sure if the x86 architecture supports 8-byte alignment even though they support a 64-bit environment. After all, 4-byte alignment on a 64-bit platform wouldn't harm anything.

You can also use: #pragma align 8 (variable) to tell the compiler how you want a global or static variable aligned.

tracy.brown