Skip to content

Instantly share code, notes, and snippets.

@0xF6
Created November 9, 2015 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xF6/089e0adff6a80dbf8bf9 to your computer and use it in GitHub Desktop.
Save 0xF6/089e0adff6a80dbf8bf9 to your computer and use it in GitHub Desktop.
Read a structure in stream
using System;
using System.IO;
public unsafe static T Read<T>(this Stream s) where T : struct
{
int i = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
byte[] buffer = new byte[i];
s.Read(buffer, 0, i);
fixed (byte* pBuffer = &buffer[0])
return (T)System.Runtime.InteropServices.Marshal.PtrToStructure((IntPtr)pBuffer, typeof(T));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment