Home > Net >  C # byte array structure, byte array is not a fixed size, can't use Marshal
C # byte array structure, byte array is not a fixed size, can't use Marshal

Time:09-23

And c + + code to transmit the socket communication, data size is not fixed, so there is no way to use Marshal for conversion,
Bitconvert structure is too much, data too big can't change, consult a great god what to do,

Public struct DemoParametersFrame,
{
Public int CMD_ID;
Public int Total_Size;
Public int Param_ID;
Public int Param_Size;
Public byte [] Param_Data;//the fixed length,
};

CodePudding user response:

Don't finish a hair ah, sent the subcontract

CodePudding user response:

Can also need not Marshal, the example is sent example, can write their own, such as use BinaryReader,

 
Public struct DemoParametersFrame
{
Public int CMD_ID;
Public int Total_Size;
Public int Param_ID;
Public int Param_Size;
Public byte [] Param_Data;//the fixed length,

Public void WriteToStream (Stream Stream)
{
If (Param_Size & lt; 0 | | Param_Size & gt; (Param_Data? .length?? 0)) throw new InvalidOperationException ();
If (Total_Size!=4 * sizeof (int) + Param_Size) throw new InvalidOperationException ();

Using (var writer=new BinaryWriter (stream, Encoding UTF8, leaveOpen: true))
{
Writer. Write (CMD_ID);
Writer. Write (Total_Size);
Writer. Write (Param_ID);
Writer. Write (Param_Size);
If (Param_Data!=null) writer. Write (Param_Data, 0, Param_Size);
}
}
}

CodePudding user response:

refer to the second floor github_36000833 response:
can also need not Marshal, the case is sent example, can write their own, such as use BinaryReader,

 
Public struct DemoParametersFrame
{
Public int CMD_ID;
Public int Total_Size;
Public int Param_ID;
Public int Param_Size;
Public byte [] Param_Data;//the fixed length,

Public void WriteToStream (Stream Stream)
{
If (Param_Size & lt; 0 | | Param_Size & gt; (Param_Data? .length?? 0)) throw new InvalidOperationException ();
If (Total_Size!=4 * sizeof (int) + Param_Size) throw new InvalidOperationException ();

Using (var writer=new BinaryWriter (stream, Encoding UTF8, leaveOpen: true))
{
Writer. Write (CMD_ID);
Writer. Write (Total_Size);
Writer. Write (Param_ID);
Writer. Write (Param_Size);
If (Param_Data!=null) writer. Write (Param_Data, 0, Param_Size);
}
}
}




This is to structure the unpacking, actually my byte array is to coming from a lot of structure, so the root of the problem is I want to find a way I can be a lot of structure into a byte array method,

CodePudding user response:

Binary serialization, or XML, json serialization, and then into a byte []
  •  Tags:  
  • C#
  • Related