2010-10-27 59 views
6

的存儲內容在遊戲中,我國防部對他們最近取得了一些變化,這打破了一個特定的實體。與別人誰想出了一個修復它溝通後,他們只信息,他們給我的是他們「修補它」,不會再分享。傾銷對象

我基本上是試圖記住如何在運行時轉儲類對象的存儲內容。我隱約記得之前做過類似的事情,但這已經很長時間了。記住如何去做這件事的任何幫助將是最感激。

回答

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"); 
} 
+0

謝謝,這正是我一直在尋找。 – 2010-10-27 09:34:05

+0

請注意,這隻適用於如果對象不包含指向其他地方的內存指針。 – doron 2010-10-27 11:22:57

+1

另外,如果你傳遞'基地*'指針,它不會打印完整的'Derived'對象,只是'Base'部分。 – MSalters 2010-10-27 11:36:18

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]) << " "; 
} 

這是醜陋的,但應該工作。

無論如何,處理內部的一些實現通常是不是一個好主意