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

时间:2022-12-30 05:26:44

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 = ;
var addr1 = getMemory(num);
Console.WriteLine($"num: hash code = {num.GetHashCode()} memory addr = {num}"); Person person = new Person() { Id = , 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 =  memory addr =
person: hash code = memory addr = 0x26810F4
请按任意键继续. . .

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

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