字符串 "abc" 在通过命名管道从 C++ 到 C# 作为 Unicode 后变为 "a[=11=]b[=11=]c[=11=]"

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

我通过 C++ 中的命名管道发送消息 "abc"(为简洁起见进行了编辑):

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

并从 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 -

问题: 收到的 message"a[=15=]b[=15=]c[=15=][=15=][=15=]" 而不是 "abc"。
我做错了什么?我在 C++/C# 上搜索了 Unicode 的所有 SO 技巧,但无济于事。

你所拥有的是每个字符编码 2 个字节,即 16 位 Unicode。这与 UTF8 不同。 UTF8 根据需要使用尽可能多的字节,因此简单的 'a' 是一个字节,但一些中文符号可以采用例如4 个字节。

您需要使用Unicode编码:

string result = Encoding.Unicode.GetString(buffer, 0, count); 

请注意,这将为您提供 'abc[=18=]' 字符串,因此会有空终止符,但这是正确的。