這是我的C ++結(jié)構(gòu)(文檔說每個(gè)實(shí)例的大小必須恰好是10個(gè)字節(jié)):#pragma pack (1)struct LaserPoint { WORD x; WORD y; byte colors[6];};我制作了以下C#結(jié)構(gòu):[StructLayout(LayoutKind.Sequential, Pack=1)]public struct LaserPoint { public UInt16 x; // 2 bytes public UInt16 y; // 2 bytes public byte[] colors; // 6 bytes}這是我的C#項(xiàng)目中的完整測試代碼:using System;using System.Runtime.InteropServices;namespace StructSizeTest { class Program { [StructLayout(LayoutKind.Sequential, Pack=1)] public struct LaserPoint { public UInt16 x; // 2 bytes public UInt16 y; // 2 bytes public byte[] colors; // byte[6] = 6 bytes } static void Main(string[] args) { LaserPoint point = new LaserPoint(); point.x = (UInt16)16384; point.y = (UInt16)32768; point.colors = new byte[6]; point.colors[0] = 255; point.colors[1] = 255; point.colors[2] = 255; point.colors[3] = 255; point.colors[4] = 255; point.colors[5] = 255; Console.WriteLine("LaserPoint.Size: " + Marshal.SizeOf(point)); Console.ReadLine(); } }}這是控制臺(tái)上的輸出:LaserPoint.Size: 8為什么是point8個(gè)字節(jié)而不是10個(gè)字節(jié)?UInt16 = 2 bytesUInt16 = 2 bytesbyte[6] = 6 bytesTotal = 10 bytes ?我在這里想念的是什么?
2 回答
慕妹3242003
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
我認(rèn)為問題出在數(shù)組上...試試這個(gè):
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
public UInt16 x; // 2 bytes
public UInt16 y; // 2 bytes
[MarhalAs(UnmanagedType.ByValArray, SizeConst = 6]
public byte[] colors; // 6 bytes
}
- 2 回答
- 0 關(guān)注
- 183 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
