2017-05-18 5 views
0

Je suis assez nouveau à C# et je dois gérer un flux d'octets que je reçois. En C++ je habituellement utilisé quelque chose comme ça:Y a-t-il quelque chose de similaire dans C# à pragma pack pour gérer un flux d'octets?

#pragma pack(push, DTA_VLS, 1) 
typedef struct tsHEADER 
{ 
    WORD    wLength;   
    WORD    wIdCounter;   
    WORD    wxxxx;  
    WORD    wxxxx2;  
} tHEADER; 
#pragma pack(pop, DTA_VLS) 

puis quand je reçu un tableau d'octets que je pouvais faire quelque chose comme ça:

tHEADER header*; 

header = receivedByteArray; 
if(header->wLength >0) 
{ 
    do something 
} 

Y at-il quelque chose de semblable que je pouvais faire en C# quand je veux lire un télégramme reçu ou en créer un nouveau? Ou puis-je faire que quelque chose comme ça:

byte[] Tel= new byte(5); 
byte[0]= Length; 
byte[1]=ID; 
// and so on 
+0

http://stackoverflow.com/a/1936208/17034 –

Répondre

0

Je pense que la meilleure chose que vous pouvez faire est d'utiliser le BinaryWriter puis faire une petite classe pour contenir les données. Vous pouvez également utiliser BinaryReader pour lire les octets de retour. Il y a un BinaryFormatter, mais je suis assez sûr qu'il a des méta-données supplémentaires cependant (ne me retenez pas à cela).

public class MyPackage 
{ 
    public int Length => 12; // or 16 if Length is included 

    public int Id { get; set; } 

    public int Number1 { get; set; } 

    public int Number2 { get; set; } 

    public byte[] SerializeToBinary() 
    { 
     using (var memoryStream = new MemoryStream()) 
     using (var writer = new BinaryWriter(memoryStream)) 
     { 

      writer.Write(Length); 
      writer.Write(Id); 
      writer.Write(Number1); 
      writer.Write(Number2); 

      return memoryStream.ToArray(); 
     } 
    } 

    public void DeserializeFromBinary(byte[] data) 
    { 
     using(var memoryStream = new MemoryStream(data)) 
     using(var reader = new BinaryReader(memoryStream)) 
     { 
      var length = reader.ReadInt32(); 
      if (length != Length) 
       throw new Exception("Some error if you care about length"); 

      Id = reader.ReadInt32(); 
      Number1 = reader.ReadInt32(); 
      Number2 = reader.ReadInt32(); 
     } 
    } 
}