【问题标题】:wstring to wchar_t conversionwstring 到 wchar_t 的转换
【发布时间】:2015-09-16 10:41:17
【问题描述】:

我正在使用 Namedpipes 通信 (C++) 在两个进程之间传输数据。为了方便起见,我使用 wstring 传输数据,传输结束时一切正常。我无法在接收端接收总数据。 以下是传输结束代码。

wstringstream send_data;        
send_data << "10" << " " << "20" << " " << "30" << " " << "40" << " " << "50" << " " << "60" << "\0" ;
DWORD numBytesWritten = 0;
result = WriteFile(
    pipe, // handle to our outbound pipe
    send_data.str().c_str(), // data to send
    send_data.str().size(), // length of data to send (bytes)
    &numBytesWritten, // will store actual amount of data sent
    NULL // not using overlapped IO
);

以下是接收端代码。

wchar_t buffer[128];
DWORD numBytesRead = 0;
BOOL result = ReadFile(
    pipe,
    buffer, // the data from the pipe will be put here
    127 * sizeof(wchar_t), // number of bytes allocated
    &numBytesRead, // this will store number of bytes actually read
    NULL // not using overlapped IO
);

if (result) {
    buffer[numBytesRead / sizeof(wchar_t)] = '\0'; // null terminate the string
    wcout << "Number of bytes read: " << numBytesRead << endl;
    wcout << "Message: " << buffer << endl;

}

缓冲区中的结果只包含 10 20 30 有人可以解释一下为什么数据被截断。

【问题讨论】:

  • 您确定数据被截断了吗?您似乎没有检查管道以查看是否有任何剩余内容等待读取。你似乎也没有检查你写的字节数是否和你认为写的一样多。
  • 从某个流中读取,你不应该期望得到一定的大小(它可能更小甚至为零)。对一些错误或 eof 条件做出反应
  • 不应该 send_data.str().size()send_data.str().size() * sizeof(wchar_t) / sizeof(char),因为您发送的是多字节字符?
  • @Hurkyl:是的,我在传输之前确实检查过,wstringstream 中的数据包含什么。所有数据似乎都存在。如果,我没记错的话,“缓冲区”应该打印管道包含的所有数据。
  • @NathanOliver:哇!不错的一个.. 现在,我得到了整个数据。非常感谢

标签: c++ named-pipes wchar-t wstring


【解决方案1】:

您并未使用WriteFile() 函数发送所有数据。您发送的send_data.str().size() 字节数不正确,因为size() 给您的是字符数而不是字节数。您可以更改您的代码以使用:

send_data.str().size() * sizeof(wchar_t) / sizeof(char)

这将发送正确数量的字节。

【讨论】:

  • / sizeof(char) 是多余且无用的,因为根据 C++ 标准,sizeof(char) 始终为 1,即使 char 在每个平台上不是 8 位(参见 CHAR_BIT)。但在 Windows 上,char 是 8 位。
  • 另外,send_data.str() 在每次调用时都会返回一个新的std::wstring。发送代码应先将send_data.str() 的结果保存到本地std::wstring 变量中,然后对该变量调用c_str()size()
  • @RemyLebeau 我意识到sizeof(char) 将始终为 1,但它有助于可视化您正在对字符的大小进行配给。由于sizeof() 是在编译时评估的,因此运行时的代码应该只乘以一个常量。
猜你喜欢
  • 1970-01-01
  • 2012-02-13
  • 2017-12-12
  • 2013-07-28
  • 1970-01-01
  • 2011-07-29
  • 2011-05-20
  • 2012-08-04
  • 1970-01-01
相关资源
最近更新 更多