在C#中序列化固定缓冲区

时间:2016-10-06 15:36:07

标签: c# serialization deserialization

是否可以在C#中序列化固定缓冲区?我正在使用.net二进制序列化。

[Serializable]
public unsafe struct MyStruct
{
   public fixed int MyArray[10];
}

为了克服这个问题,一种选择是忽略固定缓冲区并创建一个属性:

[Serializable]
public unsafe struct MyStruct
{
   [field: NonSerialized]
   public fixed int MyArray[10];

   public string MyArrayCsv
   {
      get { // populate string from array... }
      set { // populate array from string... }
   }
}

这适用于Xml序列化,但二进制序列化忽略属性。关于如何二进制序列化固定缓冲区的任何想法?

1 个答案:

答案 0 :(得分:-1)

为什么不使用BinaryFormatter

但这里有可能的解决方案(安全且不安全):

using System.IO;
using System;

public class UnsafeAndBinaryWriter
{
    public unsafe static void Main(String[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5 };
        Console.WriteLine("Hex buffer(unsafe): {0}", BitConverter.ToString(SerializeUnsafe(arr)));
        Console.WriteLine("Hex buffer        : {0}", BitConverter.ToString(Serialize(arr)));
    }
    private static unsafe byte[] SerializeUnsafe(int[] arr)
    {
        int totalSize = arr.Length * sizeof(int);
        byte[] resultBuffer = new byte[totalSize];
        // Of course you can do it without unsafe magic :)
        fixed (int* p = (&arr[0])) {
            byte* ptr = (byte*)p;
            for (int i = 0; i < totalSize; i++, ptr++)
                resultBuffer[i] = *ptr;
        }
        return resultBuffer;
    }
    private static byte[] Serialize(int[] arr)
    {
        byte[] resultBuffer = null;
        // Stream for storing result
        using (var stream = new MemoryStream()) {
            using (BinaryWriter bw = new BinaryWriter(stream)) {
                for (int i = 0; i < arr.Length; i++)
                    bw.Write(arr[i]);
            }
            resultBuffer = stream.ToArray();
        }
        return resultBuffer;
    }
}