Exemple #1
0
        public static T[] ReadStructs <T>(this Stream input, int count) where T : new()
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            T[] result = new T[count];

            if ((TypeCache <T> .Flags & TypeCacheFlags.ReadableFromStream) == TypeCacheFlags.ReadableFromStream)
            {
                for (int i = 0; i < result.Length; i++)
                {
                    T value = new T();
                    IReadableFromStream readable = (IReadableFromStream)value;
                    readable.ReadFromStream(input);
                    result[i] = value;
                }
            }
            else
            {
                int    size = Marshal.SizeOf(TypeCache <T> .Type);
                byte[] buff = new byte[size];
                using (SafeGCHandle handle = new SafeGCHandle(buff, GCHandleType.Pinned))
                {
                    for (int i = 0; i < result.Length; i++)
                    {
                        input.EnsureRead(buff, 0, size);
                        result[i] = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), TypeCache <T> .Type);
                    }
                }
            }

            return(result);
        }
Exemple #2
0
        public static void WriteStruct(this Stream output, object pack)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            int size = Marshal.SizeOf(pack);

            byte[] buff = new byte[size];

            using (SafeGCHandle handle = new SafeGCHandle(buff, GCHandleType.Pinned))
            {
                Marshal.StructureToPtr(pack, handle.AddrOfPinnedObject(), false);
                output.Write(buff, 0, size);
            }
        }