Can I implement .ToString() on C++ structs for deb

2019-04-07 07:15发布

问题:

In C#, if I define a struct, I can also override ToString(). Then when I'm debugging and I add a watch or hover my mouse over an instance of the struct, the tooltip will be the computed ToString() rather than the type name of the struct.

Can I do that in C++ and/or C++/CLI somehow? That is, can I define a method as part of the struct (or do anything else) that will cause the watch-value/tooltip to display a string of my choosing? The default string rendering in Visual Studio for C/C++ is a list of all the struct's field values (or as many as can be jammed into the little box).

My types all C-style structs. (It was actually written in C before I converted the files to .cpp and fixed some type issues so I could run it in CLI.) Here's an example struct:

struct other_dollars_node
{
    struct other_dollars_node *next_other_dollars;
    override *overrides;    
    long     other_dollars_id;
    tm       effective_date;
    double   amount;
}

I have very little experience with C++/CLI -- most of my experience has been with native C/C++ and C#. I'm using Visual Studio 2013.

Update: since almost all the existing code uses native C syntax, and I would prefer a solution that works without having to refactor it, the CLI aspect may be less important.

回答1:

I think what you want to do is to provide a debugger visualization for your native structs. I did a little searching on MSDN, and found this page: Create custom views of native objects in the debugger.

Basically, what you need to do is add a file to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Packages\Debugger\Visualizers to tell Visual Studio how to show your structs in the debugger window. There are many examples there, and the link above provides some good explanation, though I admit I haven't tried it myself.