Last active
December 20, 2024 10:04
-
-
Save 8chan-co/5fbdf2ad220d97f9c46935189bc18506 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
public static class ArrayExtensions_Dotnet | |
{ | |
#if NET5_0_OR_GREATER | |
public static unsafe int GetElementSize(this Array array) | |
{ | |
fixed (void* baseAddress = &MemoryMarshal.GetArrayDataReference(array)) | |
{ | |
// NOTE: UnsafeAddrOfPinnedArrayElement <- <pinned-array-address> + <element-index> * <element-size> | |
nint elementAddress = Marshal.UnsafeAddrOfPinnedArrayElement(array, index: 1); | |
return (int)(elementAddress - (nint)baseAddress); | |
} | |
} | |
#endif | |
} | |
public static class ArrayExtensions_Unity | |
{ | |
public static unsafe int GetElementSize(this Array array) | |
{ | |
ulong handle = 0; | |
try | |
{ | |
nint baseAddress = (nint)UnsafeUtility.PinGCArrayAndGetDataAddress(array, out handle); | |
// NOTE: UnsafeAddrOfPinnedArrayElement <- <pinned-array-address> + <element-index> * <element-size> | |
nint elementAddress = Marshal.UnsafeAddrOfPinnedArrayElement(array, index: 1); | |
return (int)(elementAddress - baseAddress); | |
} | |
finally | |
{ | |
UnsafeUtility.ReleaseGCObject(handle); | |
} | |
} | |
} | |
public static class ArrayExtensions_UnityDotnet | |
{ | |
public static int GetElementSize(this Array array) | |
{ | |
GCHandle handle = default; | |
try | |
{ | |
handle = GCHandle.Alloc(array, GCHandleType.Pinned); | |
nint baseAddress = handle.AddrOfPinnedObject(); | |
// NOTE: UnsafeAddrOfPinnedArrayElement <- <pinned-array-address> + <element-index> * <element-size> | |
nint elementAddress = Marshal.UnsafeAddrOfPinnedArrayElement(array, index: 1); | |
return (int)(elementAddress - baseAddress); | |
} | |
finally | |
{ | |
if (handle.IsAllocated) | |
{ | |
handle.Free(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment