本文介绍了在gdb中进行漂亮打印时,如何访问数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm able to get the value using ptr.dereference, however I have no idea how to increment the pointer to get the next value. Assume I'm using a 16bit signed array. How do I get the first 5 values?

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'

推荐答案

对于这个简单的数组类,取自您的其他问题:

For this simple array class, taken from your 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;
    }
};

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

I would implement the pretty printer like this:

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}

这篇关于在gdb中进行漂亮打印时,如何访问数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 02:58