MemoryManagement.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace ARMeilleure.Memory
  5. {
  6. public static class MemoryManagement
  7. {
  8. public static IntPtr Allocate(ulong size)
  9. {
  10. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  11. {
  12. IntPtr sizeNint = new IntPtr((long)size);
  13. return MemoryManagementWindows.Allocate(sizeNint);
  14. }
  15. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
  16. RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  17. {
  18. return MemoryManagementUnix.Allocate(size);
  19. }
  20. else
  21. {
  22. throw new PlatformNotSupportedException();
  23. }
  24. }
  25. public static IntPtr AllocateWriteTracked(ulong size)
  26. {
  27. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  28. {
  29. IntPtr sizeNint = new IntPtr((long)size);
  30. return MemoryManagementWindows.AllocateWriteTracked(sizeNint);
  31. }
  32. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
  33. RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  34. {
  35. return MemoryManagementUnix.Allocate(size);
  36. }
  37. else
  38. {
  39. throw new PlatformNotSupportedException();
  40. }
  41. }
  42. public static void Reprotect(IntPtr address, ulong size, MemoryProtection permission)
  43. {
  44. bool result;
  45. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  46. {
  47. IntPtr sizeNint = new IntPtr((long)size);
  48. result = MemoryManagementWindows.Reprotect(address, sizeNint, permission);
  49. }
  50. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
  51. RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  52. {
  53. result = MemoryManagementUnix.Reprotect(address, size, permission);
  54. }
  55. else
  56. {
  57. throw new PlatformNotSupportedException();
  58. }
  59. if (!result)
  60. {
  61. throw new MemoryProtectionException(permission);
  62. }
  63. }
  64. public static bool Free(IntPtr address)
  65. {
  66. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  67. {
  68. return MemoryManagementWindows.Free(address);
  69. }
  70. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
  71. RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  72. {
  73. return MemoryManagementUnix.Free(address);
  74. }
  75. else
  76. {
  77. throw new PlatformNotSupportedException();
  78. }
  79. }
  80. }
  81. }