[英]C# Marshal.SizeOf
我正在使用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));
我有两个程序。 在一个程序中,len等于8.在另一个程序中,它等于16.它是相同的结构。 为什么我有这种差异?
我猜一个程序是针对AnyCPU(在64位平台上将是64位)和一个32位编译的。
方法不会影响给定的大小,因此我们有效地谈论:
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。
它取决于机器和构建配置。 正如@Joey所说的AnyCPU或64位
有一些技巧可以避免这个问题:
例如,您可以检查:
应用程序类型Environment.Is64BitOperatingSystem
IntPtr的大小在32和64上更改
使用System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.