public static TestStruct FromFileStream(FileStream fs) { //Create Buffer byte[] buff = new byte[Marshal.SizeOf(typeof(TestStruct))]; int amt = 0; //Loop until we've read enough bytes (usually once) while(amt < buff.Length) amt += fs.Read(buff, amt, buff.Length-amt); //Read bytes //Make sure that the Garbage Collector doesn't move our buffer GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned); //Marshal the bytes TestStruct s = (TestStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(TestStruct)); handle.Free();//Give control of the buffer back to the GC return s }
public static TestStruct FromBinaryReaderBlock(BinaryReader br) { //Read byte array byte[] buff = br.ReadBytes(Marshal.SizeOf(typeof(TestStruct))); //Make sure that the Garbage Collector doesn't move our buffer GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned); //Marshal the bytes TestStruct s = (TestStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(TestStruct)); handle.Free();//Give control of the buffer back to the GC return s; }
public static TestStruct FromBinaryReaderField(BinaryReader br) { TestStruct s = new TestStruct();//New struct s.longField = br.ReadInt64();//Fill the first field s.byteField = br.ReadByte();//Fill the second field s.byteArrayField = br.ReadBytes(16);//... s.floatField = br.ReadSingle();//... return s; }