通过streamwriter将Marshal C#字符串转换为C ++ tchar

时间:2015-02-23 18:56:59

标签: c# encoding pinvoke tchar

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。建议?

2 个答案:

答案 0 :(得分:0)

这不是一个直接的答案,因为它不使用一个转码器,就像目标一样。但由于局限性,这种方法效果很好。

解决方法:

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);
}

答案 1 :(得分:0)

根据您的评论,您实际上需要UTF-16编码的文本。这与Encoding.Unicode相对应。所以你会用

new StreamWriter(pipeClient, Encoding.Unicode)

那就是说,你至少应该考虑字节序的问题。通过网络传输数据时,我希望您在结束时转换为网络字节顺序,并在接收时转换为主机字节顺序。