读\写 boost::binary_oarchive 到管道

Posted

技术标签:

【中文标题】读\\写 boost::binary_oarchive 到管道【英文标题】:Read\write boost::binary_oarchive to pipe读\写 boost::binary_oarchive 到管道 【发布时间】:2008-12-25 22:26:07 【问题描述】:

我将继续构建两个简单的进程,通过简单的(匿名)管道将类对象彼此抛出(参见我的上一篇文章)。现在我为自己揭示了 boost::serialization(感谢回答的人),并试图通过 ::WriteFile::ReadFile 对某些类进行序列化。那么 - 我做错了什么?


1) 我创建了一些类

 #pragma once
 #include "wtypes.h"
 #include <boost\archive\binary_oarchive.hpp>
 #include <boost\archive\binary_iarchive.hpp>
 #include <boost\serialization\binary_object.hpp>

 class CTextContainer
 
 friend class boost::serialization::access;
     template<class Archive>
     void serialize(Archive & ar, const unsigned int version)
     
         ar & m_sText;
         ar & m_dwCRC;
         ar & m_dwSize;
     

 public:
      CTextContainer() : m_dwCRC(0), m_dwSize(0)
      
          ZeroMemory(m_sText, sizeof(m_sText));
          m_dwSize = sizeof(*this);
      
      CTextContainer(LPCTSTR sText) : m_dwCRC(0), m_dwSize(0)
      
         ZeroMemory(m_sText, sizeof(m_sText));
         wcsncpy_s(m_sText, 1024, sText, wcslen(sText));
         m_dwSize = sizeof(*this);
      
      virtual ~CTextContainer()
      LPTSTR GetText() constreturn (LPTSTR) m_sText;
      protected:
      DWORD m_dwCRC;
      DWORD m_dwSize;
      TCHAR m_sText[1024];
 ; //end of class

2) 现在我正在尝试从此类读取二进制存档并将其内容写入管道的一端...

boost::archive::binary_oarchive oa(ofs);
oa << tc;
::WriteFile(hPipe, &oa, dwRead, &dwWritten, NULL) == FALSE 

那样不行,对吧?那么,它会如何呢?

3) 另一边的操作相同?

【问题讨论】:

【参考方案1】:

我认为这里的问题是您正在尝试将指针传递给 WriteFile 函数中的存档对象。你应该做的是提供一个指向序列化数据的指针。

std::stringstream ss;
boost::archive::binary_oarchive oa(ss);
oa << tc;
::WriteFile(hPipe, ss.str().data(), ss.str().data().size(), &dwWritten, NULL)

作为更好的选择,您应该为 binary_oarchive 构造函数提供直接写入文件句柄的 ostream 实现。

【讨论】:

【参考方案2】:

假设您为 dwRead 传递了正确的值,我认为问题在于流尚未被刷新。确保在块内创建 binary_oarchive,这样当它超出范围时,它的析构函数会刷新流。

std::ofstream ofs("filename");

    boost:archive::binary_oarchive oa(ofs);
    oa << tc;


// Set up your pipe and assign a value to dwRead
// ...

::WriteFile(hPipe, &oa, dwRead, &dwWritten, NULL);

【讨论】:

以上是关于读\写 boost::binary_oarchive 到管道的主要内容,如果未能解决你的问题,请参考以下文章

脏写 脏读 不可重复读 幻读 读偏差 写偏差 丢失更新 示例

为啥这个 plist 读/写失败?

Java 一边读边写即读一行写一行

在mysql中写超过读

对数据库执行大量读/写操作的方法

数据目录在Android中没有读/写权限