[英]Initialize struct with byte array based on header type
我的文件中有幾個結構。 我想傳遞一個字節數組並初始化該結構。 我已經嘗試過將結構轉換為字節數組,反之亦然,但是我遇到諸如“嘗試讀取或寫入受保護的內存”之類的錯誤。 因此,我認為傳遞字節數組來初始化結構可能更有效。 我的問題是結構的一部分依賴於第一個字節類型。 那么如何為它分配另一個結構?
這是代碼:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct Payload
{
MessageTypeID ID1;
MessageTypeID ID2;
Byte[] PayloadData;
public Payload(byte[] payloadArray)
{
this.ID1 = (MessageTypeID) payloadArray[0];
this.ID2 = (MessageTypeID) payloadArray[1];
switch (this.ID1)
{
case MessageTypeID.TEMPERATURE:
byte[] tempPayloadArray = new byte[payloadArray.Length - 2];
Temperature temp = new Temperature(Array.Copy(payloadArray,2,tempPayloadArray,0,payloadArray.Length - 2);
this.PayloadData = temp; <== ERROR: Cannot convert Temperature to byte[]
break;
case MessageTypeID.LEVEL:
.......
}
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Temperature
{
Byte LocalTemp;
Int16 ExternalTemp1;
Int16 ExternalTemp2;
public Temperature(byte[] tempArray)
{
this.LocalTemp = tempArray[0];
this.ExternalTemp1 = tempArray[1];
this.ExternalTemp2 = tempArray[2];
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Level
{
Byte FluidLevel;
Int16 FreshnessTimer;
Byte CalibrationChannelReading;
public Level(byte[] levelArray)
{
this.FluidLevel = levelArray[0];
this.FreshnessTimer = BitConverter.ToInt16(levelArray, 1);
this.CalibrationChannelReading = levelArray[3];
}
}
不要自己動手:使用.Net和CLR為您提供的基礎結構。
如果需要與非托管代碼進行互操作,則需要了解有關P / Invoke和編組的信息:
如果要與其他托管代碼進行互操作,則需要閱讀有關serialization
。 更多內容
您可以使用股票二進制序列化,也可以自己滾動。 無論哪種情況,您都希望對象是ISerializable
, ISerializable
需要實現一種方法即可將對象序列化為字節流: void GetObjectData( SerializationInfo info , StreamingContext context )
。
並且[暗示]相應的構造函數,用於將字節流反序列化為具有簽名constructor( SerializationInfo information, StreamingContext context)
的對象實例。
例如:
[Serializable]
public class Widget : ISerializable
{
public Widget( SerializationInfo serializationInfo , StreamingContext context )
{
// your rehydration logic here
}
public void GetObjectData( SerializationInfo info , StreamingContext context )
{
// your dehydration logic here
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.