2020-05-02 17:54:07 +00:00
|
|
|
using System;
|
2020-05-03 15:14:07 +00:00
|
|
|
using System.Collections.Concurrent;
|
2020-05-02 17:54:07 +00:00
|
|
|
|
2020-05-04 15:54:34 +00:00
|
|
|
namespace PkmnLibSharp.Utilities
|
2020-05-02 17:54:07 +00:00
|
|
|
{
|
|
|
|
public abstract class PointerWrapper : IDisposable
|
|
|
|
{
|
2020-05-04 15:35:53 +00:00
|
|
|
private readonly IntPtr _ptr;
|
|
|
|
internal IntPtr Ptr
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
|
|
|
if (_isDeleted)
|
|
|
|
{
|
|
|
|
throw new Exception("Pointer access after dispose detected. This is not legal, and will cause native exceptions.");
|
|
|
|
}
|
|
|
|
return _ptr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-02 18:30:33 +00:00
|
|
|
private bool _isDeleted = false;
|
2020-05-02 17:54:07 +00:00
|
|
|
|
2020-05-03 15:14:07 +00:00
|
|
|
private static readonly ConcurrentDictionary<IntPtr, WeakReference<object>> Cached =
|
|
|
|
new ConcurrentDictionary<IntPtr, WeakReference<object>>();
|
|
|
|
|
2020-05-02 17:54:07 +00:00
|
|
|
protected PointerWrapper(IntPtr ptr)
|
|
|
|
{
|
2020-05-04 15:35:53 +00:00
|
|
|
_ptr = ptr;
|
2020-05-03 15:14:07 +00:00
|
|
|
var weakRef = new WeakReference<object>(this);
|
|
|
|
Cached.TryAdd(ptr, weakRef);
|
|
|
|
}
|
|
|
|
|
|
|
|
internal static bool TryResolvePointer<T>(IntPtr p, out T result) where T : PointerWrapper
|
|
|
|
{
|
|
|
|
if (Cached.TryGetValue(p, out var val))
|
|
|
|
{
|
|
|
|
if (val.TryGetTarget(out var target))
|
|
|
|
{
|
|
|
|
result = (T) target;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
result = null;
|
|
|
|
return false;
|
2020-05-02 17:54:07 +00:00
|
|
|
}
|
|
|
|
|
2020-05-03 15:14:07 +00:00
|
|
|
protected abstract void DeletePtr();
|
2020-05-02 17:54:07 +00:00
|
|
|
public virtual void Dispose()
|
|
|
|
{
|
|
|
|
if (_isDeleted)
|
|
|
|
return;
|
2020-05-03 15:14:07 +00:00
|
|
|
Cached.TryRemove(Ptr, out _);
|
2020-05-02 17:54:07 +00:00
|
|
|
DeletePtr();
|
|
|
|
_isDeleted = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|