zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    ngRx 官方示例分析
    ngRx 官方示例分析
    oracle归档日志的操作
    【cocos2dx中Node类getParent和getChildByTag()】学习体会
    Objective-c调用Swift
    关于UITableView的黑线条
    Bootstrap风格button
    第7章 高级分组
    GDB 程序调试简单实践
    HDU 4548 美素数 素数题解
  • 原文地址:https://www.cnblogs.com/lsgxeva/p/10496924.html
Copyright © 2011-2022 走看看