C# Knowledge Series: Get the memory address of an object

C# object types are divided into two types: value types and reference types

The two ways of printing addresses are different

Value type:

unsafe void PrintValueTypeObjectAddress()
{
   Vector2 v1 = new Vector2();
   Vector2* pV1 = &v1;
   Debug.Log((int)pV1);
} 

 

Reference type:

 public static unsafe void PrintReferenceTypeObjectAddress(object o)
{
    GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);
    IntPtr addr = h.AddrOfPinnedObject();
    Debug.Log("0x" + addr.ToString("X"));
}

        Why do you need to use GCHandleType.Pinned for GCHandleType in the reference type (many blogs on the Internet do not explain, some even use other types), you can refer to "C# Knowledge Series: The Role of GCHandleType" , in order to prevent GC objects from shifting , If you use another GCHandleType to print the address of the same object twice, you find that it is not the same (specifically why the GC memory address is shifted during the running process, it is not clear for the time being, you have to dig deeper into Mono GC mechanism works).

        In addition, do not use the PrintReferenceTypeObjectAddress method to print the address for the value type. It will perform a boxing operation (the value type is encapsulated into an object), causing the address to be different each time.

Guess you like

Origin blog.csdn.net/qq1090504117/article/details/111676719