42

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?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Nick
  • 451
  • 1
  • 4
  • 3
  • 2
    I need to send it over the network. I got the API which need me to specify the bytes of the struct including the header + data etc – Nick Feb 10 '11 at 11:24
  • Have a look at http://stackoverflow.com/questions/2418749/c-why-sizeof-is-unsafe-and-how-to-get-size-of-a-struct-in-a-safe-way – Ray Feb 10 '11 at 11:26
  • How about http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.sizeof.aspx ? Make sure you read the information in the sub pages. – porges Feb 10 '11 at 11:27
  • There are plenty of other questions covering this already. Did you search before posting? – thecoop Feb 10 '11 at 11:27
  • Marshal.SizeOf() – Mark Lauter May 31 '23 at 02:04

2 Answers2

70

The SizeOf method does the trick.

int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Point));
Bitterblue
  • 13,162
  • 17
  • 86
  • 124
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • 3
    To be more specific, it's System.Runtime.InteropServices.Marshal.SizeOf, applied to an instance. Should return the same results as the language "sizeof" applied to the type. Example below. – Reb.Cabin Jun 06 '11 at 23:24
  • This worked in combination with Reb.Cabin's comment. Thanks, now i can actually find out whats an efficient structure and whats not. – Madmenyo May 29 '13 at 21:00
  • 2
    typeof(Point), Point is a class. With struct it gives me Exception!! Try int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(test)); – MrHIDEn Jul 13 '16 at 10:49
  • I don't think that's the size of the struct. It's the size the struct gets marshalled to. – CodesInChaos May 24 '17 at 10:02
6

You put the sizeof operator into an unsafe context just like the compiler suggests?

Something like this I guess:

int size;
unsafe
{
    size=sizeof(Test);
}

But I'm not sure if you really want to do that. I'd tend to use a normal serializer instead of structs with specific layout for this. IMO you should use such structs only for native interop and not for simple serialization.

And looking at the documentation of the SizeOf function marshalling can mess with the size too(not in this example though).

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262