From 82c5dbc93917e6f2e45f2611564fed14ddc1e63f Mon Sep 17 00:00:00 2001 From: Mikhail <99481254+DCFApixels@users.noreply.github.com> Date: Sun, 24 Dec 2023 18:11:20 +0800 Subject: [PATCH] Update ArrayUtility.cs --- src/Utils/ArrayUtility.cs | 41 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/Utils/ArrayUtility.cs b/src/Utils/ArrayUtility.cs index 9eab0b6..b70bcc5 100644 --- a/src/Utils/ArrayUtility.cs +++ b/src/Utils/ArrayUtility.cs @@ -1,4 +1,8 @@ -namespace DCFApixels.DragonECS.Utils +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System; + +namespace DCFApixels.DragonECS.Utils { internal static class ArrayUtility { @@ -12,4 +16,39 @@ array[i] = value; } } + + internal static unsafe class UnmanagedArrayUtility + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* New(int capacity) where T : struct + { + return Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T)) * capacity).ToPointer(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* NewAndInit(int capacity) where T : struct + { + int newSize = Marshal.SizeOf(typeof(T)) * capacity; + byte* newPointer = (byte*)Marshal.AllocHGlobal(newSize).ToPointer(); + + for (int i = 0; i < newSize; i++) + *(newPointer + i) = 0; + + return newPointer; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Free(void* pointer) + { + Marshal.FreeHGlobal(new IntPtr(pointer)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* Resize(void* oldPointer, int newCount) where T : struct + { + return (Marshal.ReAllocHGlobal( + new IntPtr(oldPointer), + new IntPtr(Marshal.SizeOf(typeof(T)) * newCount))).ToPointer(); + } + } }