Reputation: 49
I dont know if previously someone asked the same. When i tried to search in the net, i couldn't find it. Please help me in solving this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
public class Details
{
public uint ID;
public uint state;
public uint country;
public uint place;
}
[StructLayout(LayoutKind.Sequential)]
public class UserDetails
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public Details[] userDetails;
}
static void Main(string[] args)
{
UserDetails u = new UserDetails();
int sizeofDetails = Marshal.SizeOf(u);
}
}
}
When i executed the code, i am expecting the sizeofDetails should be 128. But i am getting 64.
Is there any problem in declaration of the array. Can someone please help?
Upvotes: 2
Views: 89
Reputation: 62005
Change class Details
to struct Details
(and repeat for UserDetails). With the changes the output should be 128 as expected.
In the original code Details is a Reference/Class type, and Details[]
is an array of 8 "references to" Detail instances and not an array of 8 Detail struct values. Since it takes 8 bytes for each "reference to", which makes sense on a 64-bit platform, then 8x8 = 64 (which is the observed output).
I'm a bit surprised there was no warning for applying StructLayout to a class, even though a class is a valid target. Maybe it is added by ReSharper? I'm fairly sure I've seen it somewhere..
Upvotes: 5