C# 获取变量或对象的栈与堆地址


C# 获取变量或对象的栈与堆地址

来源 https://www.cnblogs.com/xiaoyaodijun/p/6605070.html

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppTestDemo1
{
    class TestDemo1
    {
        
        [StructLayout(LayoutKind.Sequential)]
        public class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Sex { get; set; }
        }

        // 获取引用类型的内存地址方法
        public string getMemory(object obj)
        {
            GCHandle handle = GCHandle.Alloc(obj, GCHandleType.WeakTrackResurrection);
            IntPtr addr = GCHandle.ToIntPtr(handle);
            return $"0x{addr.ToString("X")}";
        }

        public void Test()
        {
            try
            {
                int num = 100000000;
                var addr1 = getMemory(num);
                Console.WriteLine($"num: hash code = {num.GetHashCode()} memory addr = {num}");

                Person person = new Person() { Id = 99, Name = "Mr.Tom", Sex = "Man" };
                var addr2 = getMemory(person);
                Console.WriteLine($"person: hash code = {person.GetHashCode()} memory addr = {addr2}");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }

        static void Main(string[] args)
        {
            TestDemo1 t1 = new TestDemo1();
            t1.Test();
        }
    }
}

 

 输出信息:

num: hash code = 100000000 memory addr = 100000000
person: hash code = 46104728 memory addr = 0x26810F4
请按任意键继续. . .

 

参考 函数调用的基本原理:http://www.cnblogs.com/swiftma/p/5468104.html

 

============== End

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM