Пример #1
0
        /// <summary>
        /// Serializes the structs, making PointerToStructPointers point to the area in memory where the
        /// array of pointers to the structs is stored, setting StructSize to the size of one serialized struct,
        /// and setting SerializedCount to the number of structs that have been serialized.
        /// </summary>
        public void Serialize()
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            // deallocate the previous pointers
            DeallocateSerializedStructs();

            StructSize = Marshal.SizeOf(typeof(T));

            // marshal the structs individually
            foreach (var theStruct in TheStructs)
            {
                var structPointer = Marshal.AllocHGlobal(StructSize.Value);
                StructPointers.Add(structPointer);
                Marshal.StructureToPtr(theStruct, structPointer, false);
            }

            // assemble the array of pointers to the structs
            PointerToStructPointers = Marshal.AllocHGlobal(StructPointers.Count * IntPtr.Size);
            Marshal.Copy(StructPointers.ToArray(), 0, PointerToStructPointers, StructPointers.Count);

            // store SerializedCount
            SerializedCount = TheStructs.Count;
        }
Пример #2
0
 protected void DeallocateSerializedStructs()
 {
     if (PointerToStructPointers != IntPtr.Zero)
     {
         Marshal.FreeHGlobal(PointerToStructPointers);
         PointerToStructPointers = IntPtr.Zero;
     }
     foreach (var structPointer in StructPointers)
     {
         Marshal.DestroyStructure(structPointer, typeof(T));
         Marshal.FreeHGlobal(structPointer);
     }
     StructPointers.Clear();
 }