Index: BaseRefCounted.cpp
===================================================================
--- BaseRefCounted.cpp	(revision 11648)
+++ BaseRefCounted.cpp	(working copy)
@@ -6,12 +6,72 @@
 
 #include <NsCore/BaseRefCounted.h>
 #include <NsCore/ReflectionImplementEmpty.h>
+#include <NsCore/HashMap.h>
+#include <NsCore/Ptr.h>
+#include <NsCore/SpinMutex.h>
 
 
 using namespace Noesis;
 
 
+static SpinMutex gHandlesMutex;
+static AtomicInteger gHandlesCounter;
+static HashMap<uint32_t, BaseRefCounted*> gHandlesMap;
+
+
 ////////////////////////////////////////////////////////////////////////////////////////////////////
+BaseRefCounted::~BaseRefCounted()
+{
+    NS_CHECK([&]()
+    {
+        // Note that 1 is valid when the object lives is the stack or is being manually destroyed
+        int32_t n = mRefCount.Load();
+        NS_CHECK(n == 1 || n == 0, "Unexpected RefCount(%d) deleting object at %p", n, this);
+        return true;
+    }
+    (), "");
+
+    if (mHandle != 0)
+    {
+        SpinMutex::ScopedLock lock(gHandlesMutex);
+        gHandlesMap.Erase(mHandle);
+    }
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+uint32_t BaseRefCounted::GetHandle()
+{
+    if (mHandle == 0)
+    {
+        mHandle = gHandlesCounter.IncrementAndFetch();
+
+        SpinMutex::ScopedLock lock(gHandlesMutex);
+        gHandlesMap.Insert(mHandle, this);
+    }
+
+    return mHandle;
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+Ptr<BaseRefCounted> BaseRefCounted::FromHandle(uint32_t handle)
+{
+    SpinMutex::ScopedLock lock(gHandlesMutex);
+    auto it = gHandlesMap.Find(handle);
+
+    if (it != gHandlesMap.End())
+    {
+        uint32_t refs = it->value->mRefCount.IncrementAndFetch();
+
+        if (refs > 1)
+        {
+            return Ptr<BaseRefCounted>(*it->value);
+        }
+    }
+
+    return nullptr;
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
 NS_BEGIN_COLD_REGION
 
 NS_IMPLEMENT_REFLECTION_(BaseRefCounted)
