序列化c#中的固定缓冲区

本文关键字:缓冲区 序列化 | 更新日期: 2023-09-27 18:11:58

是否可以序列化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序列化很有效,但是二进制序列化忽略属性。任何关于如何二进制序列化固定缓冲区的想法?

序列化c#中的固定缓冲区

为什么不使用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;
    }
}