/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2024. *
* *
* Use subject to the terms of the Apache License 2.0 available at *
* http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using AOT;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace LeapInternal
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr Allocate(UInt32 size, eLeapAllocatorType typeHint, IntPtr state);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void Deallocate(IntPtr buffer, IntPtr state);
public static class MemoryManager
{
///
/// Specifies whether or not a pooling strategy should be used for the
/// internal MemoryManager. If enabled, memory will be periodically
/// recycled to be used again instead of being deallocated.
///
/// An object may be reclaimed from the pool at any time on the
/// worker thread. If you are running into issues where an object
/// you are working with is being overwritten, consider making a copy,
/// or turning up the MinPoolSize.
///
public static bool EnablePooling = true;
///
/// Specifies how many objects of a specific type need to be in the pool
/// before they will start to be recycled. Turning this number up can
/// help prevent issues where objects you are working with are being
/// overwritten with new objects. Turning this number down can reduce
/// the total memory footprint used by the memory manager.
///
public static uint MinPoolSize = 64;
private static ConcurrentDictionary _activeMemory =
new ConcurrentDictionary();
private static ConcurrentDictionary> _pooledMemory =
new ConcurrentDictionary>();
[MonoPInvokeCallback(typeof(Allocate))]
public static IntPtr Pin(UInt32 size, eLeapAllocatorType typeHint, IntPtr state)
{
try
{
//Construct a key to identify the desired allocation
PoolKey key = new PoolKey()
{
type = typeHint,
size = size
};
//Attempt to find the pool that holds this type of allocation
ConcurrentQueue