[英]Convert C# String to MFC CString in C# project?
我正在用C#开发客户端。 该服务器是由使用C ++ MFC的其他人开发的,因此我无法对其进行更改。 服务器只能接受字符串数据作为CString(UTF8)。 注意:在我问这个问题之前,我已经搜索并阅读了许多线程,例如。 thread1 , thread2 , thread3等。但是他们谈论的是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):
线程“将C#中的String ^转换为c ++中的CString”是从C ++的角度(带有c ++代码)而不是像我的C#pov那样。 我只能访问用C#编写的客户端。 我无权访问用C ++编写的服务器代码,因此我无法更改服务器代码/ C ++代码上的任何内容。
我通过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();
添加的信息(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;
}
在不知道如何与C ++ MFC代码交互的情况下很难回答,但是如果您只需要UTF-8字节数组,则可以执行以下操作:
byte[] utf8data = Encoding.UTF8.GetBytes(strHello);
我怀疑您可能要使用BinaryWriter而不是StreamWriter。 您可能还需要对长度整数进行字节序转换(请参阅此线程 ,以及有关示例的此博客文章 )。
最后,服务器接受我的客户端发送的数据。 解决方案如下:-将原始字符串编码为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);
结案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.