在c/c++中内存对齐是个经常遇到的问题,现在的CPU一次读取64bit,所以Struct编译时会自动8byte对齐。
c#同样的结构体也是8byte对齐。
using System;
struct ss
{
public int a; // 4字节
// public int aa; // 4字节
public Int64 aaa;
public IntPtr b; // 32位系统4字节,64位系统8字节
// public char c; // 1 字节,无符号整数
public sbyte d; // 1 字节,有符号整数
public sbyte e; // 1 字节,有符号整数
}
class struct_test
{
public static void Main(string[] args)
{
var _s = new ss();
int _size = System.Runtime.InteropServices.Marshal.SizeOf(_s);
Console.WriteLine(_size);
_s.a = int.MaxValue;
// _s.aa = int.MaxValue;
_s.aaa = Int64.MaxValue;
_s.b = IntPtr.Zero-1;
// _s.c ='a';// char.MaxValue;
_s.d = sbyte.MaxValue;
_s.e = sbyte.MaxValue;
unsafe
{
int i = 0;
byte* p = (byte*)&_s;
Console.WriteLine("myStruct0 start:Address:{0:X2} Value:{1:d}", (int)p, (byte)(*(p + i)));
Console.WriteLine();
for (i = 0; i < _size; i++)
{
Console.WriteLine("Address:{0}={1:X} Value:{2:d}", i, (int)(p + i), (byte)(*(p + i)));
}
}
}
}
在64位时的情况:
csc struct_test.cs /unsafe
占32个字节
在32位时的情况:
csc struct_test.cs /unsafe /platform:x86
占24个字节
注意:c#中char占两个字节