MemoryHelper.cs 1.9 KB

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