Possible Duplicate:
How to check the number of bytes consumed by my Structure?
I have a struct in the packed form of
[StructLayout(LayoutKind.Sequential, Pack = 1)] public struct test { public int a; public uint16 b; }
How do I get the size of the struct as the compiler states that sizeof can only be used in unsafe context?
For 'int' and 'double', it takes up 4 and 8 bytes respectively. The compiler used the 3 wasted bytes (marked in red) to pad the structure so that all the other members are byte aligned. Now, the size of the structure is 4 + 1 +3 = 8 bytes.
struct { unsigned int widthValidated; unsigned int heightValidated; } status; This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of the variables. The C programming language offers a better way to utilize the memory space in such situations.
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
The size of the character pointer is 8 bytes.
The SizeOf
method does the trick.
int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Point));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With