在c#中将复杂结构转换为字节数组

时间:2012-03-20 09:20:20

标签: c# serialization struct byte

这是我结构的定义

    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;
    }

如何将struct SPMSifReturnKcdLclMsg转换为通过tcp / ip发送的字节数组? 原谅我的语言,我不能很好地使用英语:p

1 个答案:

答案 0 :(得分:3)

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

修改
忘了提一下你的结构应该标记为Serializable