How to convert a structure to a byte array in C#?

前端 未结 14 843
难免孤独
难免孤独 2020-11-22 09:59

How do I convert a structure to a byte array in C#?

I have defined a structure like this:

public struct CIFSPacket
{
    public uint protocolIdentifi         


        
14条回答
  •  灰色年华
    2020-11-22 10:17

    You can use Marshal (StructureToPtr, ptrToStructure), and Marshal.copy but this is plataform dependent.


    Serialization includes Functions to Custom Serialization.

    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) 
    

    SerializationInfo include functions to serialize each member.


    BinaryWriter and BinaryReader also contains methods to Save / Load to Byte Array (Stream).

    Note that you can create a MemoryStream from a Byte Array or a Byte Array from a MemoryStream.

    You can create a method Save and a method New on your structure:

       Save(Bw as BinaryWriter)
       New (Br as BinaryReader)
    

    Then you select members to Save / Load to Stream -> Byte Array.

提交回复
热议问题