Marshal.SizeOf() is giving improper size

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Charming12
    New Member
    • Sep 2008
    • 18

    Marshal.SizeOf() is giving improper size

    Hi All,

    I am using System.Runtime. InteropServices; to marshal a structure using Marshal.structu reToPtr().
    But to get the size of structure when i get Marshal.sizeOf( ), it gives me improper sizes.

    Code:

    public struct IDName
    {
    public ushort Id;
    public int IdLen;
    }

    Static void Main(string[] args)
    {
    IdName idname = new IdName();
    idname.Id = 1;
    idname.IdLen = 1;

    int size = Marshal.SizeOf( idname);
    }

    It gives me size as 8 instead of 6 i.e, ushort + int.
    If i use only ushort or only int then it shows me proper size.
    This problem is coming with byte, sbyte as well.

    Plz suggest something to get proper results.
    Thanks
    Eric
  • artov
    New Member
    • Jul 2008
    • 40

    #2
    If you use the plain struct, you allow the compiler to put the fields the way it likes. If you know how the data should be (and you seem to, since you know the real size), you should use tell it to the compiler with StructLayout attribute. I have used following when porting C code

    Code:
    [StructLayout(LayoutKind.Explicit)]
    public struct IDName
    {
        [FieldOffset(0)]
        public ushort Id;
        [FieldOffset(2)]
        public int IdLen;
    }
    but I guess StructLayout(La youtKind.Sequen tial)] might also work. The reason I have use LayoutKind.Expl icit is, I have some unions also. These can be made using same number on two (or more) FieldOffsets.

    Comment

    Working...