【问题标题】:View the contents and the value of variables in the memory查看内存中变量的内容和值
【发布时间】:2018-01-25 09:15:41
【问题描述】:

我正在尝试创建一个调试工具,它会附加到一个进程,然后查看堆栈和堆的内容。

到目前为止,我使用 CLRmd 附加到进程,然后获取堆栈和堆内变量类型的列表,但仍然无法获取元素的值。

有什么方法可以让我获得这些值吗? 为什么 Visual Studio 调试器能够做到这一点?

语言不是这里的限制因素。

【问题讨论】:

    标签: c# debugging debuggervisualizer clrmd


    【解决方案1】:

    我使用 ClrMd NuGet 包(版本 0.8.31.1)创建了以下程序来显示对象的内容,即字段名称和值:

    using System;
    using System.Diagnostics;
    using System.Linq;
    using Microsoft.Diagnostics.Runtime;
    
    namespace ClrMdTest
    {
        class Program
        {
            static void Main(string[] args)
            {    
                var live = DataTarget.AttachToProcess(
                    Process.GetProcessesByName("clrmdexampletarget")[0].Id,
                    1000, AttachFlag.Passive);
                var liveClrVersion = live.ClrVersions[0];
                var liveRuntime = liveClrVersion.CreateRuntime();
                var addresses = liveRuntime.Heap.EnumerateObjectAddresses();
    
                // The where clause does some consistency check for live debugging
                // when the GC might cause the heap to be in an inconsistent state.
                var singleObjects = from obj in addresses
                    let type = liveRuntime.Heap.GetObjectType(obj)
                    where
                        type != null && !type.IsFree && !string.IsNullOrEmpty(type.Name) &&
                        type.Name.StartsWith("SomeInterestingNamespace")
                    select new { Address = obj, Type = type};
    
                foreach (var singleObject in singleObjects)
                {
                    foreach (var field in singleObject.Type.Fields)
                    {
                        Console.WriteLine(field.Name + " =");
                        Console.WriteLine("   " + field.GetValue(singleObject.Address));
                    }
                }
    
                Console.ReadLine();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-11
      • 2011-08-05
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 2016-03-07
      • 2017-03-23
      相关资源
      最近更新 更多