4

I'm new in C#.
I'm trying to understand why the struct size is grow.
I.e:

struct Test
{
    float x;
    int y;
    char z;
}

size of Test struct is actually 10 bytes (float=4, int=4, char=2).
But when i tried to get the sizeof struct with Marshal.SizeOf(..) method i got 12.
In C++ i did pragma pack(1) to prevent this but how can i do it in C#?

Another question:
When i tried to convert the Test struct to byte array if the struct isn't [Serialize] i got byte array with size 12 bytes as excepted (or not), but if the struct is [Serialize] i got byte array with size of 170 bytes, why its happend?
Thanks! :)

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
Evyatar
  • 1,107
  • 2
  • 13
  • 36
  • *When i tried to convert the Test struct to byte array* How are you trying to do it? – xanatos Mar 01 '16 at 07:29
  • if the struct isn't [Serialize] i convert is with this method http://stackoverflow.com/questions/3278827/how-to-convert-a-structure-to-a-byte-array-in-c (the checked answer) and if soi convert it with http://stackoverflow.com/questions/628843/byte-for-byte-serialization-of-a-struct-in-c-sharp (the last answer) – Evyatar Mar 01 '16 at 07:36
  • Bear in mind that if you're using the Marshaller or serialization - you're not measuring the size of the struct. You're measuring the size of the unmanaged equivalent, or of the serialized form. Neither is necessarily related to the size of the struct itself. – Damien_The_Unbeliever Mar 01 '16 at 07:39
  • @Damien_The_Unbeliever, i dont use Marshal to know the sizeof serazlied struct. – Evyatar Mar 01 '16 at 07:54
  • What I mean is the [`Marshal.SizeOf`](https://msdn.microsoft.com/library/5s4920fa(v=vs.100).aspx): "The size returned is the size of the unmanaged type. The unmanaged and managed sizes of an object can differ" – Damien_The_Unbeliever Mar 01 '16 at 07:56

1 Answers1

10

This

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TestStruct
{
    float x;
    int y;
    char z;
}

will give a Marshal.SizeOf() == 9, because Marshal.SizeOf(typeof(char)) == 1 for strange historical reasons.

BUT

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]

with this you'll get Marshal.SizeOf() == 10

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Thanks, and what about the size of with [Serialize] – Evyatar Mar 01 '16 at 07:34
  • @Evyatar You should use the http://stackoverflow.com/questions/3278827/how-to-convert-a-structure-to-a-byte-array-in-c way both if it is serializable and if it isn't. – xanatos Mar 01 '16 at 07:47
  • @Evyatar And if you are using @CmdrTallen solution for `[Serializable]`, you are doing XML serialization, so you are serializing to an XML string. – xanatos Mar 01 '16 at 08:10