c++ - wstring 到 wchar_t 的转换

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

我正在使用 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;

}

buffer中的结果只包含10 20 30 有人能解释一下为什么数据被截断了吗?

最佳答案

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

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

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

关于c++ - wstring 到 wchar_t 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124641/

相关文章:

c++ - 使用键盘 : unintended side effects when pressing enter 将数据输入到 Qt GUI

c++ - 在 `h` 中使用标签 `hh` 或 `printf` 是否涉及未定义的行为?

c - 关于命名管道的简短阅读(matlab->linux)

linux - 命名管道和 Fortran 的问题

linux - 如何确定是否可以写入管道

c++ - wchar_t 字符数组中的奇怪符号

c++ - 为什么::boost::tie 不能与 BOOST_FOREACH 一起工作?

C++检查字符串中是否只存在以下字符

c++ - 从 wchar_t 转换为 char,反之亦然

c - 在 C 中理解和编写 wchar_t