文章目錄
- 1 C# 結構體對齊
- 1.1 默認對齊方式
- 1.2 節對齊方式設置
- 1.3 偏移量設置
- 2 C#與C/C++之間類型的對應關系
1 C# 結構體對齊
1.1 默認對齊方式
struct默認對齊方式,結構體長度必須是,最大成員長度的整數倍,所以下面結構體大小是 24
(實際占用大小為20)
using System;
using System.Runtime.InteropServices;namespace CdllTest
{class Program{static void Main(string[] args){TestStruct ts = new TestStruct();int len = Marshal.SizeOf(ts);Console.WriteLine(len);Console.ReadKey();}}public struct TestStruct{//默認對齊方式,struct長度必須是,最大成員長度的整數倍,所以下面結構體大小是 24 public byte id;//0~1public int width;//4~8public long height;//8~16public int num1;//16~20 }
}
1.2 節對齊方式設置
設置1字節對齊方式
[StructLayout(LayoutKind.Sequential,Pack = 1)]//指定1字節對齊public struct TestStruct{public byte id;//1public int width;//4public long height;//8public int num1;//4 }
1.3 偏移量設置
using System;
using System.Runtime.InteropServices;namespace CdllTest
{class Program{static void Main(string[] args){TestStruct ts = new TestStruct();int len = Marshal.SizeOf(ts);Console.WriteLine(len);Console.ReadKey();}}//指定偏移量[StructLayout(LayoutKind.Explicit)]public struct TestStruct{[FieldOffset(0)]//偏移字節數0public byte id;[FieldOffset(10)]//偏移字節數10public int width;[FieldOffset(15)]//偏移字節數15public long height;[FieldOffset(40)]//偏移字節數40public int num1; // struct長度必須是,最大成員長度的整數倍,所以結構體大小是 48 }
}