BinaryReaderExtensions.cs 896 B

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. namespace Ryujinx.Common
  5. {
  6. public static class BinaryReaderExtensions
  7. {
  8. public unsafe static T ReadStruct<T>(this BinaryReader reader)
  9. where T : struct
  10. {
  11. int size = Marshal.SizeOf<T>();
  12. byte[] data = reader.ReadBytes(size);
  13. fixed (byte* ptr = data)
  14. {
  15. return Marshal.PtrToStructure<T>((IntPtr)ptr);
  16. }
  17. }
  18. public unsafe static void WriteStruct<T>(this BinaryWriter writer, T value)
  19. where T : struct
  20. {
  21. long size = Marshal.SizeOf<T>();
  22. byte[] data = new byte[size];
  23. fixed (byte* ptr = data)
  24. {
  25. Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
  26. }
  27. writer.Write(data);
  28. }
  29. }
  30. }