C#使用Runtime.InteropServices打印变量的内存地址

  • 以前不管是在C还是OC语言以及swift中还是其他语言中,当我们认为两个变量使用的是同一块内存地址的时候
  • 最简单的方法就是直接打印地址,然而在C#中,打印地址却变得不那么容易了
    首先,需要引入System.Runtime.InteropServices;
    之后才能使用使用一些手段进行地址的打印
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));  
    }  
}  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容