C# Marshal.SizeOf

故事扮演 提交于 2019-12-10 22:12:50

问题


I am using Marshal.SizeOf to know the size of my stucture:

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. Why I got that differece?


回答1:


I'd guess one program is compiled for AnyCPU (which on a 64-bit platform will be 64-bit) and one for 32-bit.




回答2:


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. As such, it has two fields in the memory which refer to objects on the heap, or to null.

All reference type fields are 4 bytes in 32-bit .NET and 8 bytes in 64-bit .NET.

Hence the size would be 4 + 4 = 8 in 32-bit .NET or 8 + 8 = 16 in 64-bit .NET.




回答3:


It is depending on the machine and on the build configuration. As @Joey said AnyCPU or 64-Bit

There are some tricks to avoid this problem:

For example you can check:

  • The application type Environment.Is64BitOperatingSystem

  • The size of IntPtr changes on 32 and 64

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



来源:https://stackoverflow.com/questions/20003436/c-sharp-marshal-sizeof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!