gpt4 book ai didi

c# - 为什么结构 A 的大小与具有相同字段的结构 B 的大小不相等?

转载 作者:太空狗 更新时间:2023-10-29 17:33:07 24 4
gpt4 key购买 nike

为什么 struct A 的大小与 struct B 的大小不相等?

我需要做的是,它们的大小相同吗?

using System;

namespace ConsoleApplication1
{
class Program
{
struct A
{
char a;
char c;
int b;
}

struct B
{
char a;
int b;
char c;

}


static void Main(string[] args)
{
unsafe
{
Console.WriteLine(sizeof(A));
Console.WriteLine(sizeof(B));
}
Console.ReadLine();
}
}
}

输出是:

8
12

最佳答案

字段之间有一些填充。填充是使用前一个字段和下一个字段计算的。

另外,这个条件应该为真:

(size of struct) % (size of largest type) == 0

在您的例子中,最大的类型是 int,它的大小是 4 字节。

struct A
{
char a; // size is 2, no previous field, next field size is 2 - no alignment needed
char c; // size is 2, previous size is 2 -> 2 + 2 = 4, next size is 4 - no alignment needed
int b; //size is 4, it is last field, size is 4 + 4 = 8.

//current size is 2 + 2 + 4 = 8
//8 % 4 == 0 - true - 8 is final size
}

struct B
{
char a; // size is 2, next size is 4, alignment needed - 2 -> 4, size of this field with alignment is 4
int b; // size is 4, previous is 4, next size is 2(lower) - no alignment needed
char c; // size is 2, previous is 4 + 4 = 8 - no alignment needed

//current size is 4 + 4 + 2 = 10
//but size should be size % 4 = 0 -> 10 % 4 == 0 - false, adjust to 12
}

如果您希望两个结构的大小相同,您可以使用 LayoutKind.Explicit:

[StructLayout(LayoutKind.Explicit)]
public struct A
{
[FieldOffset(0)]
char a;

[FieldOffset(2)]
char c;

[FieldOffset(4)]
int b;
}

[StructLayout(LayoutKind.Explicit)]
public struct B
{
[FieldOffset(0)]
char a;

[FieldOffset(2)]
int b;

[FieldOffset(6)]
char c;
}

您可以使用 LayoutKind.SequentialPack = 1CharSet = CharSet.Unicode 来获得大小 8。

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct A
{
char a;
char c;
int b;
}

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct B
{
char a;
int b;
char c;
}

此外,您可以获得没有 unsafe 的结构大小:

Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(typeof(A)));
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(typeof(B)));

关于c# - 为什么结构 A 的大小与具有相同字段的结构 B 的大小不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com