C#Marshal.SizeOf

时间:2013-11-15 14:33:37

标签: c# size marshalling

我正在使用Marshal.SizeOf来了解我的结构大小:

struct loginStruct
{
    public string userName;
    public string password;

    public loginStruct(string userName, string password)
    {
        this.userName = userName;
        this.password = password;
    }
}

以下是此功能的使用:

int len = Marshal.SizeOf(typeof(loginStruct));

我有2个节目。在一个程序中,len等于8.在另一个程序中,它等于16。 它是相同的结构。为什么我有这种差异?

3 个答案:

答案 0 :(得分:8)

我猜一个程序是针对AnyCPU(在64位平台上将是64位)和一个32位编译的。

答案 1 :(得分:3)

方法不会影响给定的大小,因此我们有效地谈论:

struct loginStruct
{
    public string userName;
    public string password;
}

struct有两个引用类型字段。因此,它在内存中有两个字段,用于引用堆上的对象,或引用null

所有引用类型字段在32位.NET中为4个字节,在64位.NET中为8个字节。

因此在32位.NET中大小为4 + 4 = 8或在64位.NET中大小为8 + 8 = 16。

答案 2 :(得分:1)

取决于计算机和构建配置。 正如@Joey所说的AnyCPU或64位

有一些技巧可以避免这个问题:

例如,您可以检查:

  • 应用程序类型Environment.Is64BitOperatingSystem

  • IntPtr的大小在32和64

  • 上更改
  • 使用System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA)