简体   繁体   English

C#Marshal.SizeOf

[英]C# Marshal.SizeOf

I am using Marshal.SizeOf to know the size of my stucture: 我正在使用Marshal.SizeOf来了解我的结构大小:

struct loginStruct
{
    public string userName;
    public string password;

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

Here is the use of this function: 以下是此功能的用法:

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

I got 2 programs. 我有两个程序。 In one program len is equals to 8. In the other it equals to 16. It is the same struct. 在一个程序中,len等于8.在另一个程序中,它等于16.它是相同的结构。 Why I got that differece? 为什么我有这种差异?

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

Methods don't affect the size given, so effectively we're talking about: 方法不会影响给定的大小,因此我们有效地谈论:

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

That struct has two reference type fields. struct有两个引用类型字段。 As such, it has two fields in the memory which refer to objects on the heap, or to null . 因此,它在内存中有两个字段,它们引用堆上的对象,或者为null

All reference type fields are 4 bytes in 32-bit .NET and 8 bytes in 64-bit .NET. 所有引用类型字段在32位.NET中为4个字节,在64位.NET中为8个字节。

Hence the size would be 4 + 4 = 8 in 32-bit .NET or 8 + 8 = 16 in 64-bit .NET. 因此,在32位.NET中大小为4 + 4 = 8或在64位.NET中大小为8 + 8 = 16。

It is depending on the machine and on the build configuration. 它取决于机器和构建配置。 As @Joey said AnyCPU or 64-Bit 正如@Joey所说的AnyCPU或64位

There are some tricks to avoid this problem: 有一些技巧可以避免这个问题:

For example you can check: 例如,您可以检查:

  • The application type Environment.Is64BitOperatingSystem 应用程序类型Environment.Is64BitOperatingSystem

  • The size of IntPtr changes on 32 and 64 IntPtr的大小在32和64上更改

  • using System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA) 使用System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM