c++gdbpretty-printgdb-python

Display a particular std::vector's element in GDB pretty printer


Suppose I have a simple struct:

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

I want to write a pretty printer for GDB that would display vec[index] for an object of type S.

This is how I do it now:

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())

Is there a simpler way to access the given element of std::vector? Is it possible to call operator[] (in GDB I can do p s.vec[0] and get what I want)? I'd like my printer to be independent of the particular implementation of std::vector.


Solution

  • After reading this answer, I came up with the following solution:

    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']))