String "abc" becomes "a\0b\0c\0" after going through Named Pipe from C++ to C# as Unicode

Viewed 1028

I send a message "abc" via a named pipe in C++ (edited for brevity):

LPWSTR message = TEXT("abc");
hPipe = CreateFile( // Type: HANDLE
    lpszPipename,   // pipe name 
    GENERIC_READ |  // read and write access 
    GENERIC_WRITE,
    0,              // no sharing 
    NULL,           // default security attributes
    OPEN_EXISTING,  // opens existing pipe 
    0,              // default attributes 
    NULL);          // no template file
dwMode = PIPE_READMODE_MESSAGE; // DWORD
SetNamedPipeHandleState(
    hPipe,    // pipe handle 
    &dwMode,  // new pipe mode 
    NULL,     // don't set maximum bytes 
    NULL);    // don't set maximum time 
cbToWrite = (lstrlen(message) + 1)*sizeof(TCHAR); // DWORD
_tprintf(TEXT("%d bytes %s."), cbToWrite, message); // Displays: 8 bytes abc.
WriteFile(
    hPipe,                  // pipe handle 
    message,             // message 
    cbToWrite,              // message length 
    &cbWritten,             // bytes written 
    NULL);                  // not overlapped

And receive this message from C#:

NamedPipeServerStream pipeStream = new NamedPipeServerStream(
    PIPE_NAME,
    PipeDirection.InOut,
    NamedPipeServerStream.MaxAllowedServerInstances,
    PipeTransmissionMode.Message
    );
int count = pipeStream.Read(buffer, 0, 1024);
string message= System.Text.Encoding.UTF8.GetString(buffer, 0, count); // Same with UTF32
Console.OutputEncoding = System.Text.Encoding.Unicode;
Console.WriteLine("-" + message+ "-"); // Displays -a b c -

PROBLEM: Received message is "a\0b\0c\0\0\0" instead of "abc".
What did I do wrong? I searched all SO tricks for Unicode on C++/C#, to no avail.

1 Answers
Related