Connecting Tech Pros Worldwide Forums | Help | Site Map

Marshal.SizeOf() is giving improper size

Newbie
 
Join Date: Sep 2008
Posts: 18
#1: Jun 4 '09
Hi All,

I am using System.Runtime.InteropServices; to marshal a structure using Marshal.structureToPtr().
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

Member
 
Join Date: Jul 2008
Posts: 36
#2: Jun 5 '09

re: Marshal.SizeOf() is giving improper size


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

Expand|Select|Wrap|Line Numbers
  1. [StructLayout(LayoutKind.Explicit)]
  2. public struct IDName
  3. {
  4.     [FieldOffset(0)]
  5.     public ushort Id;
  6.     [FieldOffset(2)]
  7.     public int IdLen;
  8. }
  9.  
but I guess StructLayout(LayoutKind.Sequential)] might also work. The reason I have use LayoutKind.Explicit is, I have some unions also. These can be made using same number on two (or more) FieldOffsets.
Reply