2016-08-24 122 views
0

我用下面的代碼試圖序列/反序列化對象的二進制數據:穀物二進制歸檔序列化/反序列化

MyDTO dto1;  
std::ostringstream os(std::stringstream::binary); 
{ 
    cereal::BinaryOutputArchive oarchive(os); // Create an output archive 
    oarchive(dto1); 
} 

MyDTO dto2; 

std::istringstream is(os.str(), std::stringstream::binary); 
{ 
    cereal::BinaryInputArchive iarchive(is); // Create an input archive 
    try { 
     iarchive(dto2); 
    } 
    catch (std::runtime_error e) { 
     e.what(); 
    } 
} 

當代碼運行時,一個異常被捕獲與消息:

"Failed to read 8 bytes from input stream! Read 0"

任何人都可以幫助我瞭解發生了什麼問題嗎?

+0

您應該向我們展示輸入文件 – Roberto

+0

沒有輸入文件,我正在讀取和寫入字符串。 –

+1

istringstream結構是固定的,現在似乎正常工作。 –

回答

1

您的輸入檔案iarchive有沒有數據可讀,因爲is是空的。你應該使用輸出存檔先寫入stringstream,並使用相同字符串流爲iarchive從閱讀(我想這是你想要做什麼)

你應該嘗試像下面(我沒有測試):

MyDTO dto1;  
std::stringstream os(std::stringstream::binary); 
{ 
    cereal::BinaryOutputArchive oarchive(os); // Create an output archive 
    oarchive(dto1); 
} 

MyDTO dto2; 

{ 
    cereal::BinaryInputArchive iarchive(os); // Create an output archive 
    try { 
     iarchive(dto2); 
    } 
    catch (std::runtime_error e) { 
     e.what(); 
    } 
} 
+0

在簡化我的代碼時,我忽略了將ostream讀回istream的地方。問題已更新。 –

+0

你現在仍然與我所展示的IMO沒有什麼不同。你看到我的解決方案有任何問題嗎? – Arunmu

+0

那麼問題是更新,但現在沒有問題:) – Arunmu