【发布时间】:2019-08-06 13:27:40
【问题描述】:
我正在尝试将大小为 1 的字节数组转换为枚举:
public enum InformationMessageLevel : byte
{
Information = 0,
Warning = 1,
Error = 2,
Fatal = 3
}
使用编组:
// bytes = byte[1] = 0
// t is typeof(InformationMessageLevel)
unsafe
{
fixed (byte* p = bytes)
{
var localPtr = p;
return Marshal.PtrToStructure((IntPtr)localPtr, t);
}
}
但我得到了错误:
"指定的结构必须是 blittable 或有布局 信息。\r\n参数名称:结构"
我使用 IntPtr 编组的原因是,此方法用于将数据动态反序列化为不同类型的属性。
【问题讨论】:
-
t是什么? -
InformationMessageLevel result = (InformationMessageLevel) bytes[0];? -
改用
Marshal.ReadByte。此外,不要使用Marshal对不会离开托管世界的数据进行序列化/反序列化。它不是为此而设计的,它旨在在托管和非托管之间进行编组。仅托管代码有更好的序列化解决方案——JSON、BitConverter、BinaryFormatter、protobuf...不同的技术适用于不同的场景。Marshal几乎从来都不是正确的选择。 -
@DmitryBychenko 抱歉,发帖按钮应该更慢,更新问题的原因。
-
你想要的是 InformationMessageLevel[] message = new InformationMessageLevel(size)。然后使用 Marshal.PtrToStructure()。
标签: c#