将类对象转换为字节并从字节创建对象

时间:2014-12-27 01:53:10

标签: c# bytearray

我已经对这个主题做了一些研究,并在

的帮助下找到了一些解决方案
  1. MemoryStream和BinaryFormatter类
  2. 元帅班
  3. 但是这些方法都不适用于我的类,因为我的类有一个数组。

    以下是我正在使用的测试课程:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public class ByteArrayInClass
    {
        private byte _option;
        private ushort _nElements;
        private byte[] arrayElements;
    
        public ByteArrayInClass(byte option, ushort nElements)
        {
            this._option = option;
            this._nElements = nElements;
            arrayElements = new byte[nElements];
            for (int i = 0; i < arrayElements.Length; i++)
            {
                arrayElements[i] = (byte)i;
            }
        }
    
        public static byte[] ObjectToBytes(byteArrayInClass value)
        {
        }
    
        public static byteArrayInClass BytesToObject(byte[] bytes)
        {
        }
    }
    

    在我的主要:

    testObject1 = new ByteArrayInClass(3, 10);
    byte[] testBytes1 = ByteArrayInClass.ObjectToBytes(testObject1);
    
    byte[] testBytes2 = { 3, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    ByteArrayInClass testObject2 = ByteArrayInClass.BytesToObjectbyte(testBytes2);
    

    我开始认为我需要将类的成员逐个转换为字节,反之亦然,将字节转换为对象。有人能指出我正确的方向吗?

    修改 我对自己要做的事情不太清楚。我正在开发一个与服务器通信的程序。它涉及接收数据和发送数据。数据以字节发送和接收,当我收到数据字节时,我需要构造一个包含接收字节的类,所以我理解发送给我的是什么。当我向服务器发送数据时,我首先构造一个具有适当值的类,然后将对象转换为字节,这样我就可以将数据发送到服务器。希望这可以解释我想要做的事情。

    似乎没有一种简单的方法将类转换为字节,所以我自己将每个类成员转换为字节。以下是我提出的建议。如果这是完成任务的愚蠢方式,请随时告诉我。我想学习一种更聪明的方法。

    public static int GetObjectSize(ByteArrayInClass value) 
    {
        return Marshal.SizeOf(value.Option) + Marshal.SizeOf(value.ElementCount) + (value.ElementCount * 1);
    }
    
    public static byte[] ObjectToBytes(ByteArrayInClass value)
    {
        int copyIndex = 0;
        byte[] resultBytes = new byte[GetObjectSize(value)];
    
        resultBytes[copyIndex] = value.Option;
        copyIndex += 1;
    
        byte[] elementCountBytes = BitConverter.GetBytes(value.ElementCount);
        elementCountBytes.CopyTo(resultBytes, copyIndex);
        copyIndex += elementCountBytes.Length;
    
        value.ElementArray.CopyTo(resultBytes, copyIndex);
        return resultBytes;
    }
    
    
    public static ByteArrayInClass BytesTObject(byte[] bytes)
    {
        int convertIndex = 0;
        byte option = bytes[convertIndex];
        convertIndex += 1;
        ushort elementCount = BitConverter.ToUInt16(bytes, convertIndex);
        convertIndex += 2;
    
        ByteArrayInClass resultObj = new ByteArrayInClass(option, elementCount); 
        byte[] elementArray = new byte[elementCount];
        int j = 0;
        for (int i = convertIndex; i < (convertIndex + elementCount); i++)
        {
            elementArray[j++] = bytes[i];
        }
        resultObj.ElementArray = elementArray;
        return resultObj;
    }
    

4 个答案:

答案 0 :(得分:3)

好吧这也许是你在寻找

从您的评论和更新中收集的假设如下

  • 您想要一种通用的方法来序列化您的类(消息)
  • 您希望能够通过电线(插座,而不是wcf)
  • 使用它
  • 符合套接字制度
  • 您需要一些基本的防止腐败保护
  • 您希望它易于使用

注意:这里可能有很多方面可以改进,但这只是为了给你一些想法

如果您使用像webservices这样的内容,这整个答案都是空的,那么这实际上只是一种适用于套接字的序列化方法

概述

Package类有以下几种方法

  • 能够将对象序列化为字节
  • 能够将字节反序列化为对象
  • 可以使用标题信息创建包
  • 标题包含您的消息类型(选项)
  • 整个包裹的长度
  • 一些基本的检查求和和标记,如果出现损坏,您可以验证包

所以给出以下

消息枚举

// Some predefined messages
public enum MessageType : byte
{
   MyClass,
   MyOtherClass,
   Message3,
   Message4,

}

您希望通过电汇发送的某些课程

// a serilaizable class
// Make this as you like
[Serializable]
public class MyClass
{

   public byte[] SomeArbitaryBytes { get; set; }
   public string SomeArbitaryString { get; set; }
   public int SomeArbitaryInt { get; set; }
   public double SomeArbitaryDouble { get; set; }

   public MyClass()
   {

      SomeArbitaryString = "hello";
      SomeArbitaryInt = 7;
      SomeArbitaryDouble = 98.1;
      SomeArbitaryBytes = new byte[10];
      for (var i = 0; i < SomeArbitaryBytes.Length; i++)
      {
         SomeArbitaryBytes[i] = (byte)i;
      }
   }
}

套餐类

public static class Package
{
   // Method for basic checksum
   private static byte GetBasicChecksum(this byte[] data)
   {
      byte sum = 0;
      unchecked // Let overflow occur without exceptions
      {
         foreach (byte b in data)
         {
            sum += b;
         }
      }
      return sum;
   }

   // Serialize to bytes (BinaryFormatter)
   public static byte[] SerializeToBytes<T>(this T source)
   {
      using (var stream = new MemoryStream())
      {
         var formatter = new BinaryFormatter();
         formatter.Serialize(stream, source);
         return stream.ToArray();
      }
   }

   // Deerialize from bytes (BinaryFormatter)
   public static T DeserializeFromBytes<T>(this byte[] source)
   {
      using (var stream = new MemoryStream(source))
      {
         var formatter = new BinaryFormatter();
         stream.Seek(0, SeekOrigin.Begin);
         return (T)formatter.Deserialize(stream);
      }
   }

   // Check if we have enough data
   // will throw if it detects a corruption (basic)
   // return false if there isnt enough data to determine
   // return true and length of the package if sucessfull
   public static bool HasValidPackage(this Stream stream, out Int32 messageSize)
   {
      messageSize = -1;

      if (stream.Length - stream.Position < sizeof(byte) * 2 + sizeof(Int32))
         return false;


      var stx = stream.ReadByte();

      if (stx != 2)
         throw new InvalidDataException("Invalid Package : STX Failed");

      var packageLength = new byte[sizeof(Int32)];
      stream.Read(packageLength, 0, sizeof(Int32));
      messageSize = BitConverter.ToInt32(packageLength, 0) - sizeof(byte) * 3;
      var checkSum = stream.ReadByte();

      if (checkSum != packageLength.GetBasicChecksum())
         throw new InvalidDataException("Invalid Package : CheckSum Failed");

      return stream.Length >= messageSize;

   }

   // Pack the message
   public static byte[] PackMessage<T>(this T source, MessageType messageType)
   {
      var buffer = source.SerializeToBytes();
      var packageLength = BitConverter.GetBytes(buffer.Length + sizeof(byte) * 3);
      using (var stream = new MemoryStream())
      {
         stream.WriteByte(2);
         stream.Write(packageLength, 0, sizeof(Int32));
         stream.WriteByte(packageLength.GetBasicChecksum());
         stream.WriteByte((byte)messageType);
         stream.Write(buffer, 0, buffer.Length);
         stream.WriteByte(3);
         return stream.ToArray();
      }
   }

   // Unpack the message
   public static MessageType UnPackMessage(this Stream stream, Int32 messageSize, out byte[] buffer)
   {

      var messageType = (MessageType)stream.ReadByte();
      buffer = new byte[messageSize];
      stream.Read(buffer, 0, buffer.Length);

      var etx = stream.ReadByte();

      if (etx != 3)
         throw new InvalidDataException("Invalid Package : ETX Failed");

      return messageType;
   }

}

客户端代码

// create your class 
var myClass = new MyClass();

// Create a package out of it
var bytes = myClass.PackMessage(MessageType.MyClass);

服务器端代码

// this is server side
using (var stream = new MemoryStream(bytes))
{
   Int32 messageSize;

   // if we have a valid package do stuff
   // this loops until there isnt enough data for a package or empty
   while (stream.HasValidPackage(out messageSize))
   {

      byte[] buffer;

      switch (stream.UnPackMessage(messageSize, out buffer))
      {
         case MessageType.MyClass:
            var myClassCopy = buffer.DeserializeFromBytes<MyClass>();
            // do stuff with your class
            break;
         case MessageType.MyOtherClass:
            break;
         case MessageType.Message3:
            break;
         case MessageType.Message4:
            break;
         default:
            throw new ArgumentOutOfRangeException();
      }

   }

   // do something with the remaining bytes here, if any, i.e partial package

}

答案 1 :(得分:1)

C#不是C / C ++,所以你不能根据需要使用地址算法(据我所知)。

在.NET中正确转换为字节数组的方法是序列化/反序列化。

或者,如果您想要模拟低级别,可能需要BitConverter

答案 2 :(得分:1)

很难判断序列化是最终结果,还是仅仅是尝试实现其他目标的方法。迈向其他目标。然而,字节数组序列化很好:

[Serializable]
public class ByteArrayClass
{
    public byte[] FirstArray {get; set;}
    public byte[] SecondArray {get; set;}           
}

然后进行往返测试:

    ByteArrayClass myFoo = new ByteArrayClass();
    myFoo.FirstArray = new byte[] { 3, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    myFoo.SecondArray = new byte[] { 3, 11, 5, 1, 21, 23, 4, 5, 4, 7, 8, 9, 10 };

    using (FileStream fs = new FileStream(@"C:\Temp\Arry.Bin", 
                          FileMode.Create, FileAccess.Write))
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, myFoo);
    }

    ByteArrayInClass newFoo;
    using (FileStream fs = new FileStream(@"C:\Temp\Arry.Bin", 
                        FileMode.Open, FileAccess.Read))
    {
        BinaryFormatter bf = new BinaryFormatter();
        newFoo = (ByteArrayClass) bf.Deserialize(fs);
    }

如果我没有添加ProtoBuf-Net是一个比BinaryFormatter更快,更好的序列化器,那将是我的疏忽。它也更适合数据传输 - 由一个程序集序列化的类可以被另一个程序集反序列化,并产生较小的输出。

答案 3 :(得分:1)

很难说出你真正想要实现的目标,但不好意思试一试

这是否符合您的预期目标?

public class ByteArrayInClass
{
   public byte Option { get; set; }
   public ushort Elements { get; set; }
   public byte[] Bytes { get; set; }

   public ByteArrayInClass(byte option, ushort nElements)
   {
      this.Option = option;
      this.Elements = nElements;
      this.Bytes = new byte[nElements];
      for (var i = 0; i < nElements; i++)
      {
         this.Bytes[i] = (byte)i;
      }
   }
   public ByteArrayInClass(byte[] array)
   {
      this.Elements = (ushort)array.Length;
      this.Bytes = new byte[this.Elements];
      array.CopyTo(this.Bytes, 0);
   }
   public static byte[] ObjectToBytes(ByteArrayInClass value)
   {
      var result = new byte[value.Elements];
      value.Bytes.CopyTo(result, 0);
      return result;
   }

   public static ByteArrayInClass BytesToObject(byte[] bytes)
   {
      return new ByteArrayInClass(bytes);
   }
}