C#Struct结构体内存对齐

在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占两个字节

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值