这是我的C ++结构(文档说每个实例的大小必须恰好是10个字节):#pragma pack (1)struct LaserPoint { WORD x; WORD y; byte colors[6];};我制作了以下C#结构:[StructLayout(LayoutKind.Sequential, Pack=1)]public struct LaserPoint { public UInt16 x; // 2 bytes public UInt16 y; // 2 bytes public byte[] colors; // 6 bytes}这是我的C#项目中的完整测试代码: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(); } }}这是控制台上的输出:LaserPoint.Size: 8为什么是point8个字节而不是10个字节?UInt16 = 2 bytesUInt16 = 2 bytesbyte[6] = 6 bytesTotal = 10 bytes ?我在这里想念的是什么?
2 回答
慕妹3242003
TA贡献1824条经验 获得超6个赞
我认为问题出在数组上...试试这个:
[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 关注
- 162 浏览
添加回答
举报
0/150
提交
取消