-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Why Nullable<byte> is aligned to 8 bytes instead of 2 bytes as short does? #12977
Comments
This is caused by I don't know off the top of my head whether this is expected. |
Really? I've always thought of using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
Console.WriteLine("Auto: " + Unsafe.SizeOf<AutoWrapper>());
Console.WriteLine("Sequential: " + Unsafe.SizeOf<SequentialWrapper>());
}
}
[StructLayout(LayoutKind.Auto)]
internal struct AutoWrapper { public byte? One, Two; }
[StructLayout(LayoutKind.Sequential)]
internal struct SequentialWrapper { public byte? One, Two; } outputs on 64-bit:
EDIT: Fixed typos. |
The test program is looking at AutoWrapper twice. This is the expected output:
|
Argh, sorry, copy and paste error. You're right. Fixed. |
Which begs the question... why is that the case? |
Doesn't event need fields to be 16 which is weird? using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
Console.WriteLine("Auto: " + Unsafe.SizeOf<AutoWrapper>());
Console.WriteLine("Sequential: " + Unsafe.SizeOf<SequentialWrapper>());
}
}
[StructLayout(LayoutKind.Auto)]
internal struct AutoWrapper { public Nullish<byte> One, Two; }
[StructLayout(LayoutKind.Sequential)]
internal struct SequentialWrapper { public Nullish<byte> One, Two; }
[StructLayout(LayoutKind.Auto)]
internal struct Nullish<T> where T : struct
{
// No fields
} Produces
Changing Nullish to [StructLayout(LayoutKind.Sequential)]
internal struct Nullish<T> where T : struct
{
} Produces
And changing to [StructLayout(LayoutKind.Sequential)]
internal struct Nullish<T> where T : struct
{
T Value;
bool HashValue;
} Produces
|
I suspect it's this: It's odd that we don't just The CLR has had this code there since at least 2007 (that's where the TFS history cuts off). |
Use
System.Runtime.CompilerServices.Unsafe.SizeOf<T>()
andValueTuple
to do the test, seems it's always the same on different version of .net.(x86 aligned to 4 bytes)Don't know why it need such a big padding, and use 3 more times(1 more time for x86) memory than it actually needed.
The text was updated successfully, but these errors were encountered: