MemoryHelper.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 long 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. return size;
  42. }
  43. public static string ReadAsciiString(IVirtualMemoryManager memory, long position, long maxSize = -1)
  44. {
  45. using (MemoryStream ms = new MemoryStream())
  46. {
  47. for (long offs = 0; offs < maxSize || maxSize == -1; offs++)
  48. {
  49. byte value = memory.Read<byte>((ulong)(position + offs));
  50. if (value == 0)
  51. {
  52. break;
  53. }
  54. ms.WriteByte(value);
  55. }
  56. return Encoding.ASCII.GetString(ms.ToArray());
  57. }
  58. }
  59. }
  60. }