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

1
  • Marshaling to .NET String, which is well described everywhere, has nothing to do with this, you're trying to make a array<Byte> Commented Jul 6, 2012 at 4:29

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

3 Comments

@ShivShambo: Full type name added.
..thanks.. the error now says C2440: '<function-style-cast>' : cannot convert from 'const char *' to 'System::IntPtr'
@ShivShambo: Oh yeah, stupid BCL and lack of const-correctness. This edit should fix it.
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.