I managed to get the address of a .net object by
GCHandle objHandle = GCHandle.Alloc(obj,GCHandleType.WeakTrackResurrection);
int address = GCHandle.ToIntPtr(objHandle).ToInt32();
and I can recall the object by
Object obj = GCHandle.FromIntPtr(IntPtr(address)).Target;
Well, the purpose is to store the address in a native class and have an information of which native object is releated to which .net object.
AFAIK the address does not change because of allocing, is it true or does anyone have a better idea to serve my purpose?
Thanks
As Tim and thecoop has pointed out, GCHandle.Alloc may prevent garbage collection but actual object address can change as GC may move object around unless you pin the object. Further, your code is using
GCHandleType.WeakTrackResurrectionand that would not event prevent the garbage collection.GCHandle.ToIntPtrwill give address of handle that can be round-tripped over unmanaged call. Actual object address will be given byAddrOfPinnedObjectmethod.Said all that, IMO, your code may serve the purpose of associating .NET object with unmanaged object. This is because GCHandle.To/FromIntPtr will get back you correct GCHandle and you can reach your .NET object via it (provided its not garbage collected). IMO, it should be immaterial if actual object address had changed or not.