wstring转换为wchar_t

时间:2015-06-29 20:06:59

标签: 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;

}

缓冲区中的结果仅包含10 20 30 有人可以解释一下数据被截断的原因。

1 个答案:

答案 0 :(得分:0)

您没有使用WriteFile()功能发送所有数据。您发送的send_data.str().size()字节数不正确,因为size()为您提供字符数而不是字节数。您可以更改要使用的代码:

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

将发送正确的字节数。