【问题标题】:How do I access an array when pretty printing in gdb?在 gdb 中进行漂亮打印时如何访问数组?
【发布时间】:2021-02-13 12:00:00
【问题描述】:

我可以使用 ptr.dereference 获取值,但是我不知道如何增加指针以获取下一个值。假设我使用的是 16 位有符号数组。如何获得前 5 个值?

class MyArrayPrinter:
    "Print a MyArray"

    def __init__ (self, val):
        self.val = val

    def to_string (self):
        return "Array of"

    def children(self):
        ptr = self.val['array']
        #yield ('0', ptr.address[1].dereference())
        yield ('5', 47)

    def display_hint (self):
        return 'array'

【问题讨论】:

  • 这与您的其他问题中的struct MyArray 相同吗? '5'47 的值应该做什么?
  • @ssbssa:是的,和其他的一样。这些值没有任何意义,我将其用作测试,因此数组不为空

标签: gdb pretty-print


【解决方案1】:

对于这个简单的数组类,取自您的other question

template<class T>
struct MyArray
{
    int pos;
    T array[10];
    MyArray() : pos(0) {}
    void push(T val) {
        if (pos >= 10)
            return;
        array[pos++] = val;
    }
};

我会像这样实现漂亮的打印机:

class MyArrayPrinter:
    "Print a MyArray"

    class _iterator:
        def __init__ (self, start, finish):
            self.item = start
            self.finish = finish
            self.count = 0

        def __iter__ (self):
            return self

        def __next__ (self):
            count = self.count
            self.count = self.count + 1
            if self.item == self.finish:
                raise StopIteration
            elt = self.item.dereference()
            self.item = self.item + 1
            return ('[%d]' % count, elt)

        def next (self):
            return self.__next__()

    def __init__ (self, val):
        self.val = val

    def children (self):
        start = self.val['array'][0].address
        return self._iterator(start, start + self.val['pos'])

    def to_string (self):
        len = self.val['pos']
        return '%s of length %d' % (self.val.type, len)

    def display_hint (self):
        return 'array'

pp = gdb.printing.RegexpCollectionPrettyPrinter("mine")
pp.add_printer('MyArray', '^MyArray<.*>$', MyArrayPrinter)
gdb.printing.register_pretty_printer(gdb.current_objfile(), pp)

看起来像这样:

(gdb) p arr
$1 = MyArray<MyString> of length 2 = {"My test string", "has two"}
(gdb) p arr2
$2 = MyArray<MoreComplex*> of length 1 = {0x22fe00}

【讨论】:

  • tyvm。只是想知道,你这样做'[%d]' % count 有什么原因吗? str(count) 似乎工作方式相同,我想知道您是否注意到不同之处,或者是否有一种方法更合适
  • 老实说,我也不确定,但libstdc++也是这样做的,所以我只是这样做了。
猜你喜欢
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多