Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of struct in C# [duplicate]

Tags:

c#

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?

like image 979
Nick Avatar asked Feb 10 '11 11:02

Nick


People also ask

How is size of struct determined in C?

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.

How many bytes is a struct in C?

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.

Can you use sizeof on a struct in C?

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.

What is size of structure pointer in C?

The size of the character pointer is 8 bytes.


1 Answers

The SizeOf method does the trick.

int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Point)); 
like image 197
Peter Lillevold Avatar answered Oct 14 '22 09:10

Peter Lillevold