Throw exception if pointer in PointerWrapper is accessed after dispose

This commit is contained in:
Deukhoofd 2020-05-04 17:35:53 +02:00
parent 0a22959e31
commit 93c205b81f
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
1 changed files with 14 additions and 2 deletions

View File

@ -5,7 +5,19 @@ namespace PkmnLibSharp
{ {
public abstract class PointerWrapper : IDisposable public abstract class PointerWrapper : IDisposable
{ {
internal readonly IntPtr Ptr; 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;
}
}
private bool _isDeleted = false; private bool _isDeleted = false;
private static readonly ConcurrentDictionary<IntPtr, WeakReference<object>> Cached = private static readonly ConcurrentDictionary<IntPtr, WeakReference<object>> Cached =
@ -13,7 +25,7 @@ namespace PkmnLibSharp
protected PointerWrapper(IntPtr ptr) protected PointerWrapper(IntPtr ptr)
{ {
Ptr = ptr; _ptr = ptr;
var weakRef = new WeakReference<object>(this); var weakRef = new WeakReference<object>(this);
Cached.TryAdd(ptr, weakRef); Cached.TryAdd(ptr, weakRef);
} }