2017-08-17 86 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(); 
     } 
    } 
}