I have a client and a server communicating using a named pipe.
I'm trying to pass the address stored by an LPCWSTR variable from the client to the server.
To do this, I first write the address onto a wchar_t buffer, then I send the server the size of that buffer (as a DWORD), so now the server knows how many bytes it has to read. I managed to send the buffer size successfully, I'm unable to send the complete string though.
Even though the server says it has read the required number of bytes, the buffer on the server side doesn't have the entire string.
Client:
wchar_t msgBuffer[1024];
LPCWSTR lpName = L"NameString";
_swprintf(msgBuffer, _T("%p\0"), lpName); //Write data to the buffer
DWORD nBytesToWrite = wcslen(msgBuffer); //Number of bytes to be written
bWriteFile = WriteFile( //Send the buffer size
hCreateFile,
&nBytesToWrite,
(DWORD)sizeof(nBytesToWrite),
&dwNoBytesWritten,
NULL
);
bWriteFile = WriteFile( //Send the data
hCreateFile,
msgBuffer,
(DWORD)wcslen(msgBuffer),
&dwNoBytesWritten,
NULL
);
Server:
DWORD dwBytesToRead = 0;
bReadFile = ReadFile( //Read the size of the next message
hCreateNamedPipe,
&dwBytesToRead,
sizeof(DWORD),
&dwNoBytesRead,
NULL);
std::cout << "\nBytes to be read: " << dwBytesToRead;
wchar_t msg[] = L"";
bReadFile = ReadFile( //Read the data
hCreateNamedPipe,
&msg,
dwBytesToRead,
&dwNoBytesRead,
NULL);
std::cout << "\nBytes Read: " << dwNoBytesRead;// << '\n' << msg;
wprintf(L"\nMessage: %s\nSize: %zu", msg, wcslen(msg));
This is what the output on the server side is:
Bytes to be read: 9
Bytes Read: 9
Message: 78E7
Size: 5
The address is 78E7325C
on the client side, but my server only prints 78E7
Even though the server says to have read 9 bytes, the size of the resultant wchar_t is just 5, why is this?
EDIT: I've checked the buffer on the client side, it has the correct address stored. And is it okay to be sending the DWORD variable using the address-of (&) operator in WriteFile()?
The Solution
Changed (DWORD)wcslen(nBytesToWrite)
to (DWORD)sizeof(nBytesToWrite)
wcslen
gives the number of characters, whereas sizeof
gives the number of bytes, and these aren't the same.