简体   繁体   中英

convert a complex structure to byte array in c#

This is my structs' definition

    public struct SPMSifHdr
    {
        public UInt32 ui32Synch1;
        public UInt32 ui32Synch2;
        public ushort ui16Version;
        public UInt32 ui32Cmd;
        public UInt32 ui32BodySize;
    };

    struct SPMSifReturnKcdLclMsg
    {
        public SPMSifHdr hdr1;
        public char ff;
        public char[] Dta;
        public bool Debug;
        public char[] szOpId;
        public char[] szOpFirst;
        public char[] szOpLast;
    }

How to convert struct SPMSifReturnKcdLclMsg to array of bytes to send via tcp/ip?
Forgive my language, I can't use english very well :p

Socket socket = OpenSocket();
using (var stream = new NetworkStream(socket))
{
    var formatter = new BinaryFormatter();
    formatter.Serialize(stream, obj); 
}

EDIT:
Forgot to mention that your structs should be marked as Serializable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM