C#Struct结构体内存对齐

本文探讨了C#中结构体的内存对齐规则,特别是在不同位数系统下(如32位和64位)的差异。通过具体代码示例,展示了结构体成员在内存中的布局方式,以及这如何影响结构体的总大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值