ShivShambo
ShivShambo

Reputation: 521

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

Upvotes: 1

Views: 10149

Answers (3)

A.Clymer
A.Clymer

Reputation: 492

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

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283783

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());

Upvotes: 5

ShivShambo
ShivShambo

Reputation: 521

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())

Upvotes: 0

Related Questions