1

我有以下格式的 C++ 类(仅复制重要部分):

class my_stringimpl {
public:
static sample_string* create(const char* str, int len) {
    my_stringimpl* sample = static_cast<my_stringimpl*>(malloc(sizeof(my_stringimpl) + len*sizeof(char)));
    char* data_ptr = reinterpret_cast<char*>(sample+1);
    memset(data_ptr, 0, len);
    memcpy(data_ptr, str, len);
    return new (sample) my_stringimpl(len);
}   
private:
    int m_length;
};
class my_string {
public:
    my_string(const char* str, int len)
        : m_impl(my_stringimpl::create(str, len)) { }
    ~my_string() {
        delete m_impl;
    }
private:
    my_stringimpl* m_impl;
};

对于这个 my_string 类,我添加了漂亮的打印机。我在 python 脚本中添加了以下 defs(我将其包含在我的 .gdbinit 文件中) - 只是在这里复制了 func defs:

def string_to_char(ptr, length=None):
    error_message = ''
    if length is None:
        length = int(0)
        error_message = 'null string'
    else:
        length = int(length)
    string = ''.join([chr((ptr + i).dereference()) for i in xrange(length)])
    return string + error_message

class StringPrinter(object):
    def __init__(self, val):
        self.val = val 

class StringImplPrinter(StringPrinter):
    def get_length(self):
        return self.val['m_length']

    def get_data_address(self):
        return self.val.address + 1

    def to_string(self):
        return string_to_char(self.get_data_address(), self.get_length())

class MyStringPrinter(StringPrinter):
    def stringimpl_ptr(self):
        return self.val['m_impl']

    def get_length(self):
        if not self.stringimpl_ptr():
            return 0
        return StringImplPrinter(self.stringimpl_ptr().dereference()).get_length()

    def to_string(self):
        if not self.stringimpl_ptr():
            return '(null)'
        return StringImplPrinter(self.stringimpl_ptr().dereference()).to_string()

但是,在使用时我收到以下错误 -

Python Exception <class 'gdb.error'> Cannot convert value to int.: 

如果我尝试将 'ptr' 中的值更改为 int ,然后在转换回 char 之前进行算术运算(如上面的 def ),它会给出以下错误:

Python Exception <type 'exceptions.AttributeError'> 'NoneType' object has no attribute 'cast':

谁能告诉我我做错了什么?我真的很震惊这里。:(。简而言之,我正在尝试实现以下 c/c++ expr 等效项,

*(char*){hex_address}

在蟒蛇。我该怎么做?

4

1 回答 1

0

最好发布完整的堆栈跟踪,或者至少准确指出哪些行引发了异常。Python 提供了这个...

您的 string_to_char 函数可以替换为 Value.string 或 Value.lazy_string,它们正是为此用途而设计的。我想错误来自那里;在这种情况下,这应该删除它。

此外,您的打印机应该实现返回“字符串”的“提示”方法。

于 2013-10-02T19:24:04.703 回答