NativeMemoryHelper.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace NativeCollection
  5. {
  6. public static unsafe class NativeMemoryHelper
  7. {
  8. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  9. public static void* Alloc(UIntPtr byteCount)
  10. {
  11. GC.AddMemoryPressure((long)byteCount);
  12. #if NET6_0_OR_GREATER
  13. return NativeMemory.Alloc(byteCount);
  14. #else
  15. return Marshal.AllocHGlobal((int)byteCount).ToPointer();
  16. #endif
  17. }
  18. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  19. public static void* Alloc(UIntPtr elementCount, UIntPtr elementSize)
  20. {
  21. GC.AddMemoryPressure((long)((long)elementCount * (long)elementSize));
  22. #if NET6_0_OR_GREATER
  23. return NativeMemory.Alloc(elementCount, elementSize);
  24. #else
  25. return Marshal.AllocHGlobal((int)((int)elementCount*(int)elementSize)).ToPointer();
  26. #endif
  27. }
  28. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  29. public static void* AllocZeroed(UIntPtr byteCount)
  30. {
  31. GC.AddMemoryPressure((long)byteCount);
  32. #if NET6_0_OR_GREATER
  33. return NativeMemory.AllocZeroed(byteCount);
  34. #else
  35. var ptr = Marshal.AllocHGlobal((int)byteCount).ToPointer();
  36. Unsafe.InitBlockUnaligned(ptr,0,(uint)byteCount);
  37. return ptr;
  38. #endif
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public static void* AllocZeroed(UIntPtr elementCount, UIntPtr elementSize)
  42. {
  43. GC.AddMemoryPressure((long)((long)elementCount * (long)elementSize));
  44. #if NET6_0_OR_GREATER
  45. return NativeMemory.AllocZeroed(elementCount, elementSize);
  46. #else
  47. var ptr = Marshal.AllocHGlobal((int)((int)elementCount*(int)elementSize)).ToPointer();
  48. Unsafe.InitBlockUnaligned(ptr,0,(uint)((uint)elementCount*(uint)elementSize));
  49. return ptr;
  50. #endif
  51. }
  52. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  53. public static void Free<T>(T* ptr) where T : unmanaged
  54. {
  55. #if NET6_0_OR_GREATER
  56. NativeMemory.Free(ptr);
  57. #else
  58. Marshal.FreeHGlobal(new IntPtr(ptr));
  59. #endif
  60. }
  61. }
  62. }