コード例 #1
0
        /// <summary>
        /// 序列化对象,并将序列化数据写入指定的缓冲区中
        /// </summary>
        /// <typeparam name="T">序列化的对象类型</typeparam>
        /// <param name="obj">被序列化的对象</param>
        /// <param name="buffer">用于接受序列化数据的缓冲区</param>
        /// <param name="index"><paramref name="buffer"/>开始写入的索引</param>
        /// <param name="encoding">序列化使用的字符编码</param>
        /// <param name="endian">序列化使用的字节序</param>
        /// <returns>序列化数据的大小</returns>
        /// <exception cref="ArgumentException">字节数组容量不足</exception>
        public static int Serialize <T>(T obj, byte[] buffer, int index, Encoding encoding = Encoding.UTF8, Endian endian = Endian.BigEndian)
        {
            InternalTypeCache <T> .OnBeforeSerializationCallbacks?.Invoke(ref obj);

            int          memSize = InternalTypeCache <T> .ApproximateMemorySize;
            NativeMemory mem     = NativeMemory.Allocate(ref memSize);

            AccelWriter writer = new AccelWriter(&mem, encoding, endian == Endian.LittleEndian);

            writer.WriteGlobalConfig(encoding, endian);

            try
            {
                InternalTypeCache <T> .Serializer.Serialize(obj, ref writer);

                return(mem.CopyToArray(writer.ByteCount, buffer, index));
            }
            finally
            {
                mem.Dispose();
            }
        }