DragonECS/src/Utils/ArrayUtility.cs

49 lines
1.5 KiB
C#
Raw Normal View History

2023-04-24 00:19:07 +08:00
using System;
using System.Runtime.InteropServices;
2023-04-10 22:22:17 +08:00
namespace DCFApixels.DragonECS.Utils
2023-04-08 00:47:35 +08:00
{
internal static class ArrayUtility
{
public static void Fill<T>(T[] array, T value, int startIndex = 0, int length = -1)
{
if (length < 0)
length = array.Length;
else
length = startIndex + length;
for (int i = startIndex; i < length; i++)
array[i] = value;
}
}
2023-04-10 22:22:17 +08:00
internal static unsafe class UnmanagedArrayUtility
2023-04-10 22:22:17 +08:00
{
public static void* New<T>(int elementCount) where T : struct
2023-04-10 22:22:17 +08:00
{
return Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T)) * elementCount).ToPointer();
}
public static void* NewAndInit<T>(int elementCount) where T : struct
2023-04-10 22:22:17 +08:00
{
int newSizeInBytes = Marshal.SizeOf(typeof(T)) * elementCount;
byte* newArrayPointer = (byte*)Marshal.AllocHGlobal(newSizeInBytes).ToPointer();
for (int i = 0; i < newSizeInBytes; i++)
*(newArrayPointer + i) = 0;
return newArrayPointer;
2023-04-10 22:22:17 +08:00
}
public static void Free(void* pointerToUnmanagedMemory)
{
Marshal.FreeHGlobal(new IntPtr(pointerToUnmanagedMemory));
}
public static void* Resize<T>(void* oldPointer, int newElementCount) where T : struct
2023-04-10 22:22:17 +08:00
{
return (Marshal.ReAllocHGlobal(new IntPtr(oldPointer),
new IntPtr(Marshal.SizeOf(typeof(T)) * newElementCount))).ToPointer();
}
}
2023-04-08 00:47:35 +08:00
}