GCHandle to get address(pointer) of .net object

后端 未结 4 766
忘了有多久
忘了有多久 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:10

    What you are getting is not actually an address.

    As you notice, it seems to act like an address most of the time, and you can recall the object, by using GCHandle.FromIntPtr. However, the interesting issue is that you are using GCHandleType.WeakTrackResurrection.

    If your weakly referenced object gets collected (it presumably can, since it is only weakly referenced by the GCHandle), you still have the IntPtr, and you can pass it to GCHandle.FromIntPtr(). If you do so, then you get back null, assuming the IntPtr has not been recycled.

    (If the IntPtr has been recycled by the CLR for some reason, then you are in trouble. I'm not sure whether this can happen.)

    You are better off using either GCHandleType.Normal, or GCHandleType.Pinned (if you need to take the address of the object in unmanaged code), if you want a strong reference to the object.

    (To use GCHandleType.Pinned, your object must e.g. be primitive, or have [StructLayout] attribute, or be an array of such objects.)

提交回复
热议问题