1

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..

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
ShivShambo
  • 523
  • 12
  • 29
  • Marshaling to .NET String, which is well described *everywhere*, has nothing to do with this, you're trying to make a `array` – Ben Voigt Jul 06 '12 at 04:29

3 Answers3

5

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());
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
3

What about this method:

String ^sTemp;
array<Byte> ^TxData;

sTemp = "Hello";
TxData = System::Text::Encoding::UTF8->GetBytes(sTemp);

Link: http://www.electronic-designer.co.uk/visual-cpp-cli-dot-net/strings/convert-string-to-byte-array

A.Clymer
  • 472
  • 3
  • 9
0

This worked for me..Thanks to Ben

IntPtr ptr((void*)rdatastr.data());
array<Byte>^ data = gcnew array<Byte>(rdatastr.size()); 
System::Runtime::InteropServices::Marshal::Copy(ptr, data, 0, rdatastr.size())
ShivShambo
  • 523
  • 12
  • 29