将std :: string或string ^转换为c ++/cli中的字节数组

Shi*_*mbo 1 .net sockets string c++-cli tcpclient

我知道这是一个经常被问到的问题,我没有明确的答案将std :: string或String ^转换为字节数组,以便写入流进行tcp通信.

这就是我尝试过的

bool CTcpCommunication::WriteBytes(const std::string& rdatastr)
{
  bool retVal = false;

  try
  {
    if (static_cast<NetworkStream^>(stream) != nullptr)
    {
      array<Byte>^data = System::Text::Encoding::ASCII->GetBytes(rdatastr); 
      stream->Write( data, 0, data->Length ); 
    }
  }
  catch(Exception^)
  {
    // Ignore, just return false
  }
  return retVal;
}
Run Code Online (Sandbox Code Playgroud)

我知道这里GetBytes不会工作,我也检查了编组选项,将std:string转换为.NET String但是没有发现任何.有人帮我解决这个问题.

Ben*_*igt 5

编码已经正确,无需转换.只需复制:

array<Byte>^ data = gcnew array<Byte>(rdatastr.size());
System::Runtime::InteropServices::Marshal::Copy(IntPtr(&rdatastr[0]), data, 0, rdatastr.size());
Run Code Online (Sandbox Code Playgroud)