GCHandle to get address(pointer) of .net object

后端 未结 4 764
忘了有多久
忘了有多久 2020-12-06 13:29

I managed to get the address of a .net object by

GCHandle objHandle = GCHandle.Alloc(obj,GCHandleType.WeakTrackResurrection);
int address = GCHandle.ToIntPtr         


        
4条回答
  •  再見小時候
    2020-12-06 14:14

    You'll want to pin the GCHandle to stop the object moving around, as the GC moves objects around, so an unpinned pointer could become invalid. Pinning the object stops it moving:

    GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
    IntPtr ptr = handle.AddrOfPinnedObject();
    

    You'll also have to free the handle when you're done:

    handle.Free();
    

提交回复
热议问题