Search code examples
.netstringsocketsc++-clitcpclient

Converting std::string or string^ to byte array in c++/cli


I know this is a frequently asked question and I havent got a clear answer for converting a std::string or String^ to a byte array for writing in to a stream for tcp communication.

This is what I have tried

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

I know that here the GetBytes wont work and I have also checked marshalling options to convert std:string to .NET String but havent found out any.Can someone help me in solving this..


Solution

  • The encoding is already correct, no conversion needed. Just copy:

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