用于从一个基派生的类的GDB漂亮的打印机

GDB pretty printer for classes derived from one base

本文关键字:派生 GDB 打印机 漂亮 一个 用于      更新时间:2023-10-16

我想在我的.gdbinit中添加一个漂亮的打印机,它将用于从包含"value"的基类base派生的任何类型。这部分起作用:

class MyBasePrinter(gdb.printing.PrettyPrinter):
def __init__(self, val):
self.__val = val['value']
def to_string(self):
return self.__val
my_pretty_printer = gdb.printing.RegexpCollectionPrettyPrinter('my_printer')
my_printer.add_printer('Base', '^Base.*$', MyBasePrinter)

不幸的是,我在gdb中打印的是这样的东西:

$1 = {<Base class stuff> = <value>}

基类是一个CRTP模板,所以"基类的东西"相当长。或者,我可以为我的每个派生类添加一个单独的漂亮打印机,在这种情况下打印效果很好,但每次有人从Base派生新类时,都需要更改.gdbinit。我想知道是否有更好的解决方案?理想情况下,我希望看到类似的打印

$1 = <Derived> = <value>

基本和派生的最小代码示例:

template <typename RawType, typename T, template <typename> typename...Traits>
struct IntegralValue : Traits<T>... {
using raw_type = RawType;
raw_type value;
explicit IntegralValue(raw_type v) : value(v) { }
void operator=(IntegralValue const& rhs) { value = rhs.value; }
};
template <typename T> struct EqualComparable {
bool operator==(T rhs) const {
return static_cast<T const*>(this)->value == rhs.value;
}
bool operator!=(T rhs) const {
return static_cast<T const*>(this)->value != rhs.value;
}
};
template <typename T> struct Incrementable {
T operator++(int) {
auto& self = static_cast<T&>(*this);
T retval = self;
self.value++;
return retval;
}
// other increment-related operators here
// ...
};
struct SequenceNumber : IntegralValue<uint64_t, SequenceNumber, EqualComparable, Incrementable> {
explicit SequenceNumber(raw_type v) : IntegralValue(v) { }
};
struct Id : IntegralValue<uint64_t, Id, EqualComparable> {
explicit Id(raw_type v) : IntegralType(v) { }
};
auto id = Id(1);
auto s = SequenceNumber(2);
// stop gdb around here and print id and s

您的代码有:

my_pretty_printer = gdb.printing.RegexpCollectionPrettyPrinter('my_printer')

虽然gdb漂亮的打印机按照类型的名称注册是传统的——而且有像这样的助手可以让它更简单——但实际上并不需要。相反,你可以有一个识别器,它可以接受任何值,并决定是否为其构建一个漂亮的打印机

请参阅手册中关于gdb.pretty_printers的章节。您的识别器可以通过检查值的类型来查看它是否是从Base派生的。