Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I implement .ToString() on C++ structs for debugging purposes?

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.

like image 466
Overlord Zurg Avatar asked Oct 27 '14 21:10

Overlord Zurg


People also ask

Why we use ToString() in c#?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.

Does c# have a ToString method?

ToString() Method in C# with examples. ToString method is inherited from the Object class which is used to get a string that represents the current object. It can also apply on the Stack. It returns a string which represents the current stack object.

How do I override a string in CPP?

class string{ char* str; public: string (char* str2){ str = str2; std::cout << str2 << std::endl ; } bool operator==(char* str2) { std::cout << "c++ => " << str << "==" << str2 << std::endl; return false; } compare(char* str2) { std::cout << "c++ => " << str << "==" << str2 << std::endl; return 0; } };


1 Answers

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.

like image 135
David Yaw Avatar answered Sep 28 '22 15:09

David Yaw