StructIOExtension.cs 920 B

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace Ryujinx.Common
  7. {
  8. public static class StructIOExtension
  9. {
  10. public unsafe static T ReadStruct<T>(this BinaryReader reader) where T : struct
  11. {
  12. int size = Marshal.SizeOf<T>();
  13. byte[] data = reader.ReadBytes(size);
  14. fixed (byte* ptr = data)
  15. {
  16. return Marshal.PtrToStructure<T>((IntPtr)ptr);
  17. }
  18. }
  19. public unsafe static void WriteStruct<T>(this BinaryWriter writer, T value) 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. }