2

我有以下结构

[Serializable()]
public struct Transfer_packet 
  {
     public int  _packet_type; // 0 is action 1 is data
     public int _packet_len; // length of data
     public byte[] _data;//Content of data it's Length depends on objects types 

        public byte[] serialize()
        {
            byte[] arr;
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, this);
            arr = ms.ToArray();
           return arr;
        }
    }

在我的代码中的一些地方我这样做

            Transfer_packet sndpkt;  
            string cmd = "Some Commands in text or binary bytes";
            byte[] data = ASCIIEncoding.ASCII.GetBytes(cmd);
            sndpkt._packet_type = 0; // Action Packet 
            sndpkt._packet_len = data.Length;  // Length of command
            sndpkt._data = data;
            byte[] SendData = sndpkt.serialize();
            LanAdapter.Send(SendData, System.Net.Sockets.SocketFlags.None); // LanAdapter ->TcpSocket

struct 中的serialize函数不能正常工作我想要一个byte结构的序列数组,用于通过网络发送它并在其他用 c++ 编写的应用程序中以相同的内存格式接收它。

4

3 回答 3

1

您可以实现ISerializable接口
MSDN示例可以服务

于 2013-03-10T07:18:10.380 回答
1

您想检查protobuf-net以获得高性能、平台无关、对象序列化。恕我直言,这是最好的。

使用必要的属性修改您的对象:

[ProtoBuf.ProtoContract]
public struct Transfer_packet
{
    [ProtoBuf.ProtoMember(1)]
    public int _packet_type; // 0 is action 1 is data
    [ProtoBuf.ProtoMember(2)]
    public int _packet_len; // length of data
    [ProtoBuf.ProtoMember(3)]
    public byte[] _data;//Content of data it's Length depends on objects types 

    /// <summary>
    /// Private constructor required by protobuf
    /// </summary>
    private Transfer_packet() { }
}

用法是一块蛋糕:

// write to a file
Serializer.Serialize(outputStream, Transfer_packet);

// read from a file
var person = Serializer.Deserialize<Transfer_packet>(inputStream);
于 2013-03-10T14:01:56.370 回答
0

我将结构内的序列化函数更改Transfer_packet为这个,它对我来说很好,但我想要一个智能解决方案而不是这个,编组和 Iserialize 添加一些标题或将实际字节数组更改为一些我不知道的东西。

 public struct Transfer_packet 
        {
            public short  _packet_type; // 0 is action 1 is data
            public int _packet_len; // length of data
            public byte[] _data;//Content of data it's Length depends on objects types 

            public byte[] serialize()
            {
                byte[] arr;
                MemoryStream ms = new MemoryStream();
                arr = BitConverter.GetBytes(this._packet_type);
               // Array.Reverse(arr);
                ms.Write(arr, 0, arr.Length);
                arr = BitConverter.GetBytes(this._packet_len);
               // Array.Reverse(arr);
                ms.Write(arr,0,arr.Length);
                ms.Write(this._data, 0, this._data.Length);
                arr = ms.ToArray();
               return arr;
            }
        }
于 2013-03-10T08:22:57.867 回答