在C#项目中将C#String转换为MFC CString?

时间:2015-05-10 21:04:13

标签: c# c++ string mfc c-strings

我正在用C#开发一个客户端。服务器是由其他使用C ++ MFC的人开发的,所以我无法改变它。服务器只能接受字符串数据为CString(UTF8)。 注意:在我提出这个问题之前,我已经搜索并阅读了许多帖子,例如。 thread1thread2thread3等等。但是他们谈论C ++项目或C ++上下文中的转换(从CString到其他或从C ++ String到CString等),它们也是不在C#中。

请给我一个示例代码或指向我的链接。提前谢谢。

以下是我的示例代码。它是一个C#控制台应用程序:

class Program
{
    static void Main(string[] args)
    {
        String strHello = "Hello in C# String"; // immutable

        // How to convert ito MFC CString equivalent? CString is mutable.

    }
}

添加信息(1):

  1. 线程“将c#中的字符串^转换为c ++中的CString”是从C ++的角度来看(使用c ++代码),而不是像我的C#pov。我只能访问我的客户端,它是用C#编写的。我无法访问用C ++编写的服务器代码,因此我无法更改服务器代码/ C ++代码上的任何内容。

  2. 我通过TCP发送数据。连接成功建立。在服务器端,接收器(OnReceiveData)使用CString作为参数。以下是我的发送数据代码(在使用Agent Ron的答案之后)。它仍然不起作用,意味着:服务器仍然忽略数据。

            tcpClient = new TcpClient(hostname, port);
            Byte[] data = Encoding.UTF8.GetBytes(message);   
            NetworkStream stream = _client.GetStream();
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            writer.AutoFlush = false;
            writer.Write(data.Length);
            writer.Write(message);
            writer.Flush();
    
  3. 添加了信息(2):

    最后,我可以联系服务器的开发人员。他不会告诉我服务器的代码,但只给我他的C ++客户端的代码片段,他说它适用于他的服务器。

    int XmlClient::SendLine( const CString& strSend )
    {
        char* source = CConversion::TcharToChar( strSend ); // UTF8 conversion
        int length = strlen( source );
        char* tmp = new char[length+3];
        memcpy_s( tmp, length+3, source, length );
        tmp[ length ] = '\0';
        strcat_s( tmp, length+3, "\r\n" );
        Send( tmp, length +2 );
        delete[] tmp;
        delete[] source;
        return 0;
    }
    

2 个答案:

答案 0 :(得分:1)

如果不知道如何与C ++ MFC代码连接,很难回答,但如果你只需要一个UTF-8字节数组,你可以这样做:

byte[] utf8data = Encoding.UTF8.GetBytes(strHello);

对更新的响应

我怀疑您可能希望使用BinaryWriter而不是StreamWriter。您可能还需要对长度整数进行字节顺序转换,请参阅this thread,以及此blog post示例)。

答案 1 :(得分:0)

最后,服务器接受我的客户端发送的数据。这是解决方案: - 将原始字符串编码为UTF8并附加“\ r \ n”。 - 开放网络流。 - 只需在不使用任何作家的情况下发送它。

尽管如此,我感谢你们所有人试图通过展示找到解决方案的可能方向来帮助我。

            // Translate the passed message into UTF8 and store it as a Byte array.
            Byte[] utf8source = UTF8Encoding.UTF8.GetBytes(strHello);
            Byte[] suffix = UTF8Encoding.UTF8.GetBytes("\r\n");
            Byte[] utf8Result = new byte[utf8source.Length + suffix.Length];
            Buffer.BlockCopy(utf8source, 0, utf8Result, 0, utf8source.Length);
            Buffer.BlockCopy(suffix, 0, utf8Result, utf8source.Length, suffix.Length);

            // Send the message to the connected TcpServer. 
            NetworkStream stream = _client.GetStream();
            stream.Write(utf8Result, 0, utf8Result.Length);

案件已关闭!