MemoryHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Ryujinx.Memory;
  2. using System;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace Ryujinx.Cpu
  7. {
  8. public static class MemoryHelper
  9. {
  10. public static void FillWithZeros(IVirtualMemoryManager memory, long position, int size)
  11. {
  12. int size8 = size & ~(8 - 1);
  13. for (int offs = 0; offs < size8; offs += 8)
  14. {
  15. memory.Write<long>((ulong)(position + offs), 0);
  16. }
  17. for (int offs = size8; offs < (size - size8); offs++)
  18. {
  19. memory.Write<byte>((ulong)(position + offs), 0);
  20. }
  21. }
  22. public unsafe static T Read<T>(IVirtualMemoryManager memory, long position) where T : struct
  23. {
  24. long size = Marshal.SizeOf<T>();
  25. byte[] data = new byte[size];
  26. memory.Read((ulong)position, data);
  27. fixed (byte* ptr = data)
  28. {
  29. return Marshal.PtrToStructure<T>((IntPtr)ptr);
  30. }
  31. }
  32. public unsafe static void Write<T>(IVirtualMemoryManager memory, long position, T value) where T : struct
  33. {
  34. long size = Marshal.SizeOf<T>();
  35. byte[] data = new byte[size];
  36. fixed (byte* ptr = data)
  37. {
  38. Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
  39. }
  40. memory.Write((ulong)position, data);
  41. }
  42. public static string ReadAsciiString(IVirtualMemoryManager memory, long position, long maxSize = -1)
  43. {
  44. using (MemoryStream ms = new MemoryStream())
  45. {
  46. for (long offs = 0; offs < maxSize || maxSize == -1; offs++)
  47. {
  48. byte value = memory.Read<byte>((ulong)(position + offs));
  49. if (value == 0)
  50. {
  51. break;
  52. }
  53. ms.WriteByte(value);
  54. }
  55. return Encoding.ASCII.GetString(ms.ToArray());
  56. }
  57. }
  58. }
  59. }