我的程序中有struct
,我需要使用该大小为struct的实例分配托管内存。我已尝试使用sizeof(),但我收到以下错误:
Cannot take the address of, get the size of, or declare a pointer to a managed type('StatusType')
'StatusType' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.RunTime.InteropServices.Marshal.SizeOf)
为什么会这样?我正确使用sizeof()
(在类型名称上)。使用Marshal.SizeOf()
是不正确的,因为我不使用非托管代码。什么是正确的方法?
我的struct
如下:
[StructLayout(LayoutKind.Sequential)]
struct StatusType
{
ushort VehID;
ushort Location;
ushort Destination;
// Note: the way Intel Byte-swaps, the 16-bit definition below is "backwards" from the way a human may view things
[FlagsAttribute]
enum firstByte : uint
{
Battery = 2,
Reverse = 1,
LiveDINO = 1,
ActuallyCharging = 1,
BothLoads = 2,
AttemptingToCharge = 1
};
[FlagsAttribute]
enum secondByte : uint
{
Manual = 1,
AutoReady = 1,
Released = 1,
Unused1 = 1,
CVS = 3,
RequestStop = 1
};
// End byte-swap note
[FlagsAttribute]
enum thirdByte : ushort { CmdParsingError = 8 };
[FlagsAttribute]
enum fourthByte : ushort { Error = 8 };
[FlagsAttribute]
enum fifthByte : ushort
{
TagReadCycles = 4,
Unused = 4
};
[FlagsAttribute]
enum sixthByte : ushort { Condition = 8 };
byte[] Tag;
ushort CCUInputs;
[StructLayout(LayoutKind.Sequential)]
struct union
{
ushort ShortCheckSum;
ushort DestParam;
}
ushort CurrentLiftHeight;
ushort PCLInputs;
[FlagsAttribute]
enum seventhByte : ushort
{
Unused2 = 8
};
[FlagsAttribute]
enum eigthByte : ushort
{
BatteryVoltage = 6,
Unused3 = 2
};
ushort LongCheckSum;
}
答案 0 :(得分:3)
我猜byte[] Tag;
是你的问题。看看this MSDN article。
特别是这句话:
blittable类型的一维数组,例如整数数组。但是,包含blittable类型的可变数组的类型本身不会是blittable。