Unity3d 开发技术Unity高级进阶教程unity3D技术分享

C#使用Runtime.InteropServices打印变量的

2016-11-08  本文已影响67人  Zok93吖
using System;  
// 获取地址需要引入的库  
using System.Runtime.InteropServices;   
  
class MainClass  
{  
    public static string getMemory(object o) // 获取引用类型的内存地址方法  
    {  
        GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);  
        IntPtr addr = h.AddrOfPinnedObject();  
        return "0x" + addr.ToString("X");  
    }  
  
    public static void Main (string[] args)  
    {  
  
        int[] a = new int[1];  
        int[] b = new int[1];  
        // b=0 ,未赋值前b的地址是:0x8008E8  
        Console.WriteLine("b={0,-2},未赋值前b的地址是:{1}",  b[0],getMemory(b));  
        a[0] = 3;  
        b = a;// 此句赋值是b引用a的地址,此时a和b表示同一个内存空间地址  
        b[0] = 33;  
  
        // b=33,赋值后b的地址是:0x8008D0  
        Console.WriteLine("b={0},赋值后b的地址是:{1}",  b[0],getMemory(b));  
  
        // a=33,a的地址是:0x8008D0  
        Console.WriteLine("a={0},a的地址是:{1}",  a[0],getMemory(a));  
    }  
}  
上一篇 下一篇

猜你喜欢

热点阅读