How to visualize a column order matrix with natvis like a 2d array

483 Views Asked by At

I have a struct

struct Matrix2d
{
    // Column first ordered elements
    vector<int> m_elements;
    int m_numRows;
    int m_numCols;
};

m_elements stores {0, 1, 2, 3, 4, 5, 6, 7, 8} to represent the 2d matrix

0, 3, 6
1, 4, 7
2, 5, 8

I want to display this like below: enter image description here

Using ArrayItems feature in Natvis, I am able to come down with: enter image description here

Using natvis code:

  <Type Name="Matrix2d">
    <Expand>
      <ArrayItems>
        <Direction>Backward</Direction>
        <Rank>2</Rank>
        <Size>$i==0?m_numRows:m_numCols</Size>
        <ValuePointer>&amp;m_elements[0]</ValuePointer>
      </ArrayItems>
    </Expand>
  </Type>

But this is really ugly and I'd rather have each row be a single item than each element being an item, like how array2d is visualized.

How would you write the code in Natvis such that Matrix2d can be visualized in such way?

1

There are 1 best solutions below

0
On

For such structures, I prefer to use CustomListItems. In your case it might look like this:

  <Type Name="Matrix2d">
    <Expand>
      <CustomListItems>
        <Variable Name="i" InitialValue="0"/>
        <Loop Condition="i  &lt; m_numRows">
          <Item Name="{i}">&amp;m_elements[i * m_numCols],[m_numCols]na</Item>
          <Exec>++i</Exec>
        </Loop>
      </CustomListItems>
    </Expand>
  </Type>

Example:

struct Matrix2d
{
    Matrix2d(int r, int c) : m_numRows(r), m_numCols(c), m_elements(r * c, 0) {}
    // Column first ordered elements
    std::vector<int> m_elements;
    int m_numRows;
    int m_numCols;
};
Matrix2d g(4, 3);

example