I wrote a custom container that represents a vector (I know I could just use std::vector, this is for education purposes). The class contains a pointer to some data and I’d really like to be able to see the data instead of just the value of the pointer when I’m debugging.
If I run the C++ code below using gdb and vscode and inspect the variable x
, I get the following:
Even though I can’t see the contents of the vector, vscode recognizes that x
is an object and I can collapse it to show less.
To show the data in the vector, I wrote a pretty printer (also listed below). If I use that, vscode shows the following:
The data is shown, but it is not being recognized as an object that can be collapsed it just shows the JSON string. Note that without the pretty-printer -exec print x
in the debug console just outputs {size = 3, data = 0x55555556b2b0}
so I thought it would be reasonable that JSON strings get formatted nicely.
What would it take to properly format these strings? Maybe a special formatting of my JSON? Maybe I just switch to lldb? Any help is appreciated.
// test_vector.cpp
#include <iostream>
#include <cassert>
class my_vector {
public:
my_vector(int n) : size(n), data(new double[n]) {}
~my_vector() {
delete[] data;
}
double& operator[](int i) {
assert(i >= 0 && i < size);
return data[i];
}
private:
int size;
double* data;
};
int main()
{
my_vector x(3);
x[0] = 1;
x[1] = 2;
x[2] = 3;
return 0;
}
// vector.py
class VectorPrinter:
def __init__(self, val):
self.val = val
def to_string (self):
n = self.val['size']
data = self.val['data']
out = "{"
out += "size = " + str(n)
out += ", data_ = {"
for i in range(n-1):
out += str(data[i]) + ", "
out += str(data[n-1])
out += "}"
out += "}"
return out
def lookup_type (val):
lookup_tag = val.type.tag
if lookup_tag is None:
return None
if( lookup_tag == "my_vector" ):
return VectorPrinter(val)
return None
gdb.pretty_printers.append (lookup_type)