我正在尝试创建以下结构:
[StructLayout(LayoutKind.Explicit, Size=14)]
public struct Message
{
[FieldOffset(0)]
public ushort X;
[FieldOffset(2)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst=5)]
private ushort[] Y;
[FieldOffset(12)]
public ushort Z;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
无法从程序集中加载"消息"类型,因为它包含偏移4处的对象字段,该字段未正确对齐或由非对象字段重叠.
有谁知道为什么这会导致错误?
注意:我不能使用Pack因为我正在使用紧凑的框架.谢谢.
如果你想看到实际的例外,你需要一台64位的机器.我已经创建了一些可以解决问题的虚拟类.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class InnerType
{
char make;
char model;
UInt16 series;
}
[StructLayout(LayoutKind.Explicit)]
public class OutterType
{
[FieldOffset(0)]
char blah;
[FieldOffset(1)]
char blah2;
[FieldOffset(2)]
UInt16 blah3;
[FieldOffset(4)]
InnerType details;
}
class Program
{
static void Main(string[] args)
{
var t = new OutterType();
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在64 clr上运行它,我收到一个类型加载异常,
System.TypeLoadException was unhandled
Message="Could not load type 'Sample.OutterType' from assembly 'Sample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or …Run Code Online (Sandbox Code Playgroud)