wstring到wchar_t的转换

wstring to wchar_t conversion

本文关键字:转换 wchar wstring      更新时间:2023-10-16

我使用Namedpipes通信(C++)在两个进程之间传输数据。为了方便起见,我使用wstring来传输数据,并且在传输端一切都很好。我无法在接收端接收全部数据。以下是传输结束代码。

wstringstream send_data;        
send_data << "10" << " " << "20" << " " << "30" << " " << "40" << " " << "50" << " " << "60" << "" ;
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)] = ''; // null terminate the string
    wcout << "Number of bytes read: " << numBytesRead << endl;
    wcout << "Message: " << buffer << endl;
}

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

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

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

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