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