我想做以下事情:
- [StructLayout(LayoutKind.Sequential,Pack = 1)]
- public struct SomeStruct
- {
- public byte SomeByte;
- public int SomeInt;
- public short SomeShort;
- public byte SomeByte2;
- }
是否有替代方案,因为紧凑框架不支持Pack?
更新:显式设置结构并为每个提供FieldOffset都不起作用,因为它不会影响结构的打包方式
Update2:如果您尝试以下操作,CF程序甚至不会运行,因为结构的打包方式如下:
- [StructLayout(LayoutKind.Explicit,Size=8)]
- public struct SomeStruct
- {
- [FieldOffset(0)]
- public byte SomeByte;
- [FieldOffset(1)]
- public int SomeInt;
- [FieldOffset(5)]
- public short SomeShort;
- [FieldOffset(7)]
- public byte SomeByte2;
- }
我知道这似乎很难相信,但如果你尝试它,你会看到.将它添加到CF项目并尝试运行它,您将获得TypeLoadException.将偏移分别更改为0,4,8,10并且它将起作用(但是大小最终为12).
我希望也许某人有一个使用反射的解决方案可能单独编组每个字段类型的大小(涉及递归以处理结构或类型数组中的结构).
解决方法
这可能不是您正在寻找的答案类型,但无论如何我会发布它的地狱:
- public struct SomeStruct
- {
- public byte SomeByte;
- public int SomeInt;
- public short SomeShort;
- public byte SomeByte2;
- public byte[] APIStruct
- {
- get
- {
- byte[] output = new byte[8];
- output[0] = this.SomeByte;
- Array.Copy(BitConverter.GetBytes(this.SomeInt),output,1,4);
- Array.Copy(BitConverter.GetBytes(this.SomeShort),5,2);
- output[7] = this.SomeByte2;
- return output;
- }
- set
- {
- byte[] input = value;
- this.SomeByte = input[0];
- this.SomeInt = BitConverter.ToInt32(input,1);
- this.SomeShort = BitConverter.ToInt16(input,5);
- this.SomeByte2 = input[7];
- }
- }
- }
基本上它在APIStruct属性中进行打包/解包.