首页 > 解决方案 > 如何将通用链表中的数据类型传递给 GDB 打印命令?

问题描述

我正在用 Python 为这个链表数据结构编写一个漂亮的 GDB 打印机:

struct listNode {
    void                 *data;         /* node's data                       */
    struct listNode      *next;         /* next node in list                 */
};


struct xlist {
    struct listNode      *head;         /* head of the list                  */
    struct listNode     **tail;         /* addr of last node's 'next' ptr    */
    struct listIterator  *iNext;        /* iterator chain for list_destroy() */
    ListDelF              fDel;         /* function to delete node data      */
    int                   count;        /* number of nodes in list           */
};

typedef struct xlist * List;

数据字段是 void* 因为它是通用的,所以它会根据需要转换为适当的指针类型。下面是我漂亮的打印机,它可以很好地为某种类型(print_field_t)进行硬编码,但我正在寻找一种将所需类型作为参数传递给打印机的方法。据我所知,API 不支持此功能,但有没有办法实现此功能或等效功能?

#!/usr/bin/env python3
import gdb.printing
import gdb

class ListPrinter(object):
    '''Print a List object'''

    class _iterator:
        def __init__(self, current):
            self.current = current
            self.count = 0
            self.end = False

        def __iter__(self):
            return self

        def __next__(self):
            if self.end:
                raise StopIteration

            type = gdb.lookup_type('print_field_t').pointer()
            value = self.current['data'].cast(type).dereference()

            self.current = self.current['next']
            self.count += 1
            if self.current == 0:
                self.end = True
            return (str(self.count), value)

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

    def to_string(self):
        return 'List({}):'.format(self.val['count'])

    def children(self):
        return self._iterator(self.val['head'])

    def display_hint(self):
        return 'array'

def build_pretty_printer():
    pp = gdb.printing.RegexpCollectionPrettyPrinter('List')
    pp.add_printer('List Printer', '^List$', ListPrinter)
    return pp

gdb.printing.register_pretty_printer(gdb.current_objfile(), build_pretty_printer())

标签: clinked-listgdbpretty-printgdb-python

解决方案


推荐阅读