Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is pack size ?

Tags:

c#

.net

unmanaged

I was reading about unmanaged code in C#, and came across the following line:-

In a C# program CLR finds the offset using field tokens.
C field names are directly compiled into offsets. For access speed each field is placed at an offset that is a multiple of field's size.
That multiplier is however restricted to a maximum of x bytes, where x is the "pack size".

My question is that what is Pack Size ?

like image 627
Pratik Singhal Avatar asked Nov 22 '25 18:11

Pratik Singhal


1 Answers

I'll take the details of field alignment as a given, covered in devshorts' quote. The pack size setting is where the compiler stops trying to keep a field aligned because it is too big.

It is a compiler setting or a #pragma in native code. A tricky one on Intel processors because they are flexible and allow misaligned data with little to no penalty. A pack size of 8 is a very common default and almost always correct. Sometimes it is 1 or 4. The Pack property in your [StructLayout] declaration must match, if it doesn't then you'll have good odds for reading garbage because you'll read a field at the wrong memory location.

like image 188
Hans Passant Avatar answered Nov 24 '25 06:11

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!