【问题标题】:Display a particular std::vector's element in GDB pretty printer在 GDB 漂亮的打印机中显示特定的 std::vector 元素
【发布时间】:2018-12-22 08:25:08
【问题描述】:

假设我有一个简单的struct:

struct S {
    int index;        
    const std::vector<int>& vec;
};

我想为 GDB 编写一个漂亮的打印机,它会为 S 类型的对象显示 vec[index]

这就是我现在的做法:

class SPrinter:
    def __init__(self, name, val):
        self.val = val

    def to_string(self):
        i = int(self.val['index'])
        ptr = self.val['vec']['_M_impl']['_M_start'] + i
        return str(ptr.dereference())

有没有更简单的方法来访问std::vector 的给定元素?是否可以拨打operator[](在GDB 中我可以拨打p s.vec[0] 并得到我想要的)?我希望我的打印机独立于 std::vector 的特定实现。

【问题讨论】:

    标签: c++ gdb pretty-print gdb-python


    【解决方案1】:

    阅读this answer后,我想出了以下解决方案:

    def get_vector_element(vec, index):
        type = gdb.types.get_basic_type(vec.type)
        return gdb.parse_and_eval('(*(%s*)(%s))[%d]' % (type, vec.address, index))
    
    class SPrinter(object):
        def __init__(self, name, val):
            self.val = val
    
        def to_string(self):
            return get_vector_element(self.val['vec'], int(self.val['index']))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多