2017-08-17 45 views
0

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

直到现在我使用CLRmd来附加到一个进程,然后获取堆栈和堆内的变量类型列表,但仍然无法获取元素的值。

有没有什么方法可以让我能够得到值? visual studio调试器怎么能够做到这一点?

语言不是这里的限制。

回答

0

我创建了下面的程序与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(); 
     } 
    } 
}