visual-studionatvis

Natvis type alias feature similar to typedef


I have some complex Item expressions where the type casts of nested template types are getting quite long and difficult to read. Is it possible to 'store' a type in the Natvis definition for reuse in the expression?

For example, in the following screenshot, the arrow is pointing to a type that I am casting to which is also being reused in the expression later. For readability and maintainability, it would be great if this can be aliased where we can then use the alias directly:

enter image description here


Solution

  • The Natvis framework has no provision for naming types. Type names will always have to be spelled out. The only exception is the $T<n> macro for referencing template parameters (but that isn't useful here).

    Not all is lost, though. You can use a standard feature of programming languages to structure code: functions. The Natvis framework calls them <Intrinsic>s. They are wildly underdocumented and the best reference is the Natvis schema. They must have a Name and Expression, and can take <Parameter>s.

    As an example here is an implementation for casting expressions:

    <Intrinsic Name="cast_to_foo" Expression="(Foo*)ptr">
      <Parameter Name="ptr" Type="void*"/>
    </Intrinsic>
    

    This can subsequently be used in expressions using regular function call syntax, e.g.,

    <Expand>
      <Item Name="Foo">cast_to_foo(this)</Item>
    </Expand>
    

    This doesn't eliminate the duplication of type names but at least no longer clutters the actual visualizer expansion code. Also worth noting: <Intrinsic>s can call other <Intrinsic>s which can substantially improve readability.