通过 streamwriter 将 C# 字符串编组为 C++ tchar
Marshal C# string to C++ tchar through streamwriter
Related question
在 C++ 中,我需要一个 TCHAR 字符串 (LPTSTR)。
C# StreamWriters 可以输出 ASCII、Unicode、UTF32 等...不是 TCHAR 字符串。
我不是在调用 C++ 中的函数,而是通过命名管道发送字符串消息。
C#:
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut))
using (StreamWriter sw = new StreamWriter(pipeClient, Encoding.UTF8))
using (StreamReader sr = new StreamReader(pipeClient, Encoding.Unicode))
{
pipeClient.Connect();
pipeClient.ReadMode = PipeTransmissionMode.Message;
sw.Write("Howdy from Kansas");
sw.Flush();
var b = sr.ReadLine();
Console.Write(b);
}
C++ 需要一个 TCHAR。建议?
这不是一个直接的答案,因为它没有像目标那样使用 streamwriter。但是由于限制,这种方法工作得很好。
解决方法:
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut))
{
pipeClient.Connect();
pipeClient.ReadMode = PipeTransmissionMode.Message;
var msg = Encoding.Unicode.GetBytes("Hello from Kansas!");
pipeClient.Write(msg, 0, msg.Length);
}
根据您的意见,您实际上需要 UTF-16 编码的文本。这对应于 Encoding.Unicode
。所以你会使用
new StreamWriter(pipeClient, Encoding.Unicode)
也就是说,你至少也应该考虑字节顺序的问题。当通过网络传输数据时,我希望您在结束时转换为网络字节顺序,并在接收时转换为主机字节顺序。
Related question
在 C++ 中,我需要一个 TCHAR 字符串 (LPTSTR)。 C# StreamWriters 可以输出 ASCII、Unicode、UTF32 等...不是 TCHAR 字符串。
我不是在调用 C++ 中的函数,而是通过命名管道发送字符串消息。
C#:
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut))
using (StreamWriter sw = new StreamWriter(pipeClient, Encoding.UTF8))
using (StreamReader sr = new StreamReader(pipeClient, Encoding.Unicode))
{
pipeClient.Connect();
pipeClient.ReadMode = PipeTransmissionMode.Message;
sw.Write("Howdy from Kansas");
sw.Flush();
var b = sr.ReadLine();
Console.Write(b);
}
C++ 需要一个 TCHAR。建议?
这不是一个直接的答案,因为它没有像目标那样使用 streamwriter。但是由于限制,这种方法工作得很好。
解决方法:
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut))
{
pipeClient.Connect();
pipeClient.ReadMode = PipeTransmissionMode.Message;
var msg = Encoding.Unicode.GetBytes("Hello from Kansas!");
pipeClient.Write(msg, 0, msg.Length);
}
根据您的意见,您实际上需要 UTF-16 编码的文本。这对应于 Encoding.Unicode
。所以你会使用
new StreamWriter(pipeClient, Encoding.Unicode)
也就是说,你至少也应该考虑字节顺序的问题。当通过网络传输数据时,我希望您在结束时转换为网络字节顺序,并在接收时转换为主机字节顺序。