次の形式の 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スクリプトに次の定義を追加しました(.gdbinitファイルに含めています)-ここにコピーされたfunc定義のみ:
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}
パイソンで。どうすればいいですか?