转储对象的内存内容

时间:2010-10-27 09:17:57

标签: c++

在我为他们制作的游戏中,他们最近做了一些改变,打破了一个特定的实体。在与找到解决方法的人交谈之后,他们只有他们给我的信息是他们“修补了”并且不再共享。

我基本上试图记住如何在运行时转储类对象的内存内容。我依旧记得以前做过类似的事,但已经很久了。任何有关如何解决这个问题的帮助都将非常感激。

2 个答案:

答案 0 :(得分:6)

template <class T>
void dumpobject(T const *t) {
    unsigned char const *p = reinterpret_cast<unsigned char const *>(t);
    for (size_t n = 0 ; n < sizeof(T) ; ++n)
        printf("%02d ", p[n]);
    printf("\n");
}

答案 1 :(得分:2)

好吧,你可以reinterpret_cast将你的对象实例作为char数组显示出来。

Foo foo; // Your object
 // Here comes the ugly cast
const unsigned char* a = reinterpret_cast<const unsigned char*>(&foo);

for (size_t i = 0; i < sizeof(foo); ++i)
{
  using namespace std;
  cout << hex << setw(2) << static_cast<unsigned int>(a[i]) << " ";
}

这很难看,但工作。

无论如何,处理某些实现的内部结构通常不是一个好主意

相关问题