I am trying to trace managed object creation/disposing in a CLI/C++ prog:
::System::Diagnostics::Trace::WriteLine(String::Format(
"Created {0} #{1:X8}",
this->GetType()->Name,
((UInt64)this).ToString()));
Which fails with
error C2440: 'type cast' : cannot convert from 'MyType ^const ' to 'unsigned __int64'
Is there a way to keep track of the unique object IDs this way?
Thanks!
First of all, why this doesn’t work. Managed handle types
^aren’t pointers. They aren’t just addresses. An instance of a managed type can and will be moved around in memory by GC, so addresses aren’t stable; hence why it wouldn’t let you do such a cast (as GC can execute at any moment, and you do not know when, any attempt to use such an address as a raw value is inherently a race condition).Another thing that is often recommended, but doesn’t actually work, is
Object.GetHashCode(). For one thing, it returns anint, obviously not enough to be unique on x64. Furthermore, the documentation doesn’t guarantee that values are unique, and they actually aren’t in 2.0+.The only working solution is to create a an instance of
System.Runtime.InteropServices.GCHandlefor your object, and then cast it toIntPtr– that is guaranteed to be both unique, and stable.