title: Marshal.SizeOf Giving The Wrong Size
body: <p>The code below is giving the wrong size when using Marshal.SizeOf, but I'm not sure why.</p>
  
  <p>Here is the Struct I'm trying to get the size of:</p>
  
  <pre><code>//[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
  //[Serializable]
  [StructLayout(LayoutKind.Sequential, Pack = 1)]
  struct BLEGenericMsg
  {
      public BLEMessageHdr msg_hdr;
      public byte[] msg_body;
  
      public BLEGenericMsg(int messageSize)
      {
          msg_hdr = new BLEMessageHdr();
          msg_body = new byte[messageSize];
      }
  };
  </code></pre>
  
  <p>Here is the code that populates the struct and calls the serialize function:</p>
  
  <pre><code>    BLEGenericMsg hostKeyMsg = new BLEGenericMsg(serializedPublicBytes.Length);
      hostKeyMsg.msg_hdr.msg_id = MESSAGE_BASE_EVENT + EVENT_HOST_PUBLIC_KEY;
  
      hostKeyMsg.msg_body = serializedPublicBytes;
  
      //Only get the size of the body for the entire message, not counter or header
      hostKeyMsg.msg_hdr.msg_body_sz = (uint)hostKeyMsg.msg_body.Length;
      BluetoothLEHardwareInterface.Log("public Key Size: " + hostKeyMsg.msg_hdr.msg_body_sz + "\n");
  
      byte[] temp = Serialize(hostKeyMsg);
      BluetoothLEHardwareInterface.Log("temp Size: " + (uint)temp.Length + "\n");
  </code></pre>
  
  <p>Here is the serialize function that is getting the size of the struct:</p>
  
  <pre><code>public static byte[] Serialize&lt;T&gt;(T s)
      where T : struct
  {
      var size = Marshal.SizeOf(typeof(T));
      BluetoothLEHardwareInterface.Log("BLEGenericMsg Size: " + size + "\n");
      var array = new byte[size];
      var ptr = Marshal.AllocHGlobal(size);
      Marshal.StructureToPtr(s, ptr, true);
      Marshal.Copy(ptr, array, 0, size);
      Marshal.FreeHGlobal(ptr);
      return array;
  }
  </code></pre>
  
  <p>The size of serializedPublicBytes is 91 bytes, 
  the rest of the struct is 6 bytes. 
  So I'm expecting the Marshal.SizeOf to be 97 bytes, 
  but instead it is showing only about 14 or 16 bytes.
  I tried giving the size of msg_body at instantiation, but that didn't make a difference.
  What am I missing?</p>
  
  <p>**edit Here is here is the BLEMessageHdr struct:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
  struct BLEMessageHdr
  {
      public ushort msg_id;
      public uint msg_body_sz;
  };
  </code></pre>