Search code examples
c#sossosexclrmd

Get primitive value with ClrMD


I have the following

class Test
{
    private MyStruct myStruct;
}

struct MyStruct
{
    private int structValue;
}

How can I get the value of structValue?

I tried the following but with no success

field.GetFieldValue(_address, true\false)
field.GetFieldAddress(_address, true\false)
innerField.Type.GetValue(address)

('field' is Test variable and 'innerField' is Test.myStruct. Both are ClrInstanceField type).


Solution

  • The easy way to get the value would be to use ClrType.GetFieldValue.

    var testType = heap.GetTypeByName("QuickLab.Test");
    ulong testAddress = ...;
    int value = (int)testType.GetFieldValue(testAddress, new [] { "myStruct", "structValue" });
    

    However ClrType.GetFieldValue has been made obsolete in the latest version of ClrMD (0.8.27). Here is how to do it with the new version, note that ClrField.GetFieldValue has been renamed ClrField.GetValue.

    var testType = heap.GetTypeByName("QuickLab.Test");
    var myStructType = heap.GetTypeByName("QuickLab.MyStruct");
    
    var myStructField = testType.GetFieldByName("myStruct");
    var structValueField = myStructType.GetFieldByName("structValue");
    
    ulong testAddress = ...;
    
    // Get the address of MyStruct
    ulong myStructAddress = myStructField.GetAddress(testAddress);
    
    // Get the value in structValue field, interior = true because we are in a value type
    int value = (int)structValueField.GetValue(myStructAddress, interior:true);
    

    You might want to take a look at ClrMD.Extensions, its a library designed to make ClrMD easier to use. Here is how to do it with ClrMD.Extensions.

    ClrMDSession session = ClrMDSession.LoadCrashDump(filePath);
    ulong testAddress = ...;
    var o = session.Heap.GetClrObject(testAddress);
    int value = (int)o.Dynamic.myStruct.structValue;