0

I have the following struct:

    public struct TestStruct
    {
        public uint eventType; //4 bytes

        public uint agentMode; //4 bytes
    }

On using the code below

var structTest = new TestStruct();
int size = Marshal.SizeOf<TestStruct>(structTest);

It return me 8 bytes, as expected. If I change the struct to the following:

  public struct TestStruct
  {
      public ushort extErrorCode; //2 bytes
  }

It returns me 2 bytes, as expected too. The weird part comes now: if I change the struct like this:

    public struct TestStruct
    {
        public uint eventType; // 4 bytes

        public uint agentMode; // 4 bytes

        public ushort extErrorCode; // 2 bytes
    }

It should return me 10 bytes, right? Well, it's returning me 12 bytes! That makes no sense!

enter image description here

Why does this happen?

halfer
  • 19,824
  • 17
  • 99
  • 186
Marcel James
  • 834
  • 11
  • 20
  • 1
    No, it should be 12 ... because of padding – Selvin Aug 04 '21 at 15:26
  • Remember that `Marshal.SizeOf` returns the size that the struct would occupy after marshalling -- it doesn't tell you the size that it occupies in the CLR: for that, use [`sizeof`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof) – canton7 Aug 04 '21 at 15:27
  • 1
    In this particular case, because the `uint` has an alignment of 4 bytes, the structure as a whole will be padded out to a multiple of 4 bytes. This ensures that if you have an array of structs, the `uint` members in each struct are aligned to a 4-byte boundary. See "Rule 2" in [this answer](https://stackoverflow.com/a/67258551/1086121) – canton7 Aug 04 '21 at 15:31
  • @canton7 and guys, thx for answer! So, lets say I MUST pass this struct as byte array to another software, and that software waits a 10 BYTE array, I need to convert it manually on C#? Os is there another workarround? – Marcel James Aug 04 '21 at 16:06
  • You can set pack to 1, see the linked answer – canton7 Aug 04 '21 at 16:08
  • But, it would be much clearer to just write these manually. It's only 3 calls to `BinaryPrimitives.WriteXXX`: shorter than defining your struct, in fact – canton7 Aug 04 '21 at 16:11

0 Answers0