【发布时间】:2023-03-04 10:19:01
【问题描述】:
我试图理解为什么一个只包含 int 的结构在一个类中占用 8 个字节的内存。
考虑以下代码;
static void Main()
{
var rand = new Random();
var twoIntStruct = new TwoStruct(new IntStruct(rand.Next()), new IntStruct(rand.Next()));
var twoInt = new TwoInt(rand.Next(), rand.Next());
Console.ReadLine();
}
public readonly struct IntStruct
{
public int Value { get; }
internal IntStruct(int value)
{
Value = value;
}
}
public class TwoStruct
{
private readonly IntStruct A;
private readonly IntStruct B;
public TwoStruct(
IntStruct a,
IntStruct b)
{
A = a;
B = b;
}
}
public class TwoInt
{
private readonly int A;
private readonly int B;
public TwoInt(
int a,
int b)
{
A = a;
B = b;
}
}
现在,当我使用 dotMemory 分析这两个实例时,我得到以下结果:
虽然 int 和 intStruct 都在堆栈上占用 4 个字节的内存,但看起来堆上的类大小不同,并且该结构始终与 8 个字节对齐。
什么会导致这种行为?
【问题讨论】:
-
在
TwoStruct上使用[StructLayoutAttribute(LayoutKind.Sequential, Pack = 4)]似乎可以解决这个问题。 -
@GuruStron 直到今天我才知道
StructLayoutAttribute可以添加到课程中! -
@Sweeper 最近在docs 中发现了它=)
-
除非您想实现与其他语言的互操作性(例如使用 P/Invoke 的 C/C++),或者与平面文件记录等,否则没有特别的理由来定义 StructLayout。 stackoverflow.com/questions/381244/purpose-of-memory-alignment
标签: c# .net-core memory struct memory-alignment