ShivShambo ShivShambo - 1 year ago 171
C++ Question

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;

if (static_cast<NetworkStream^>(stream) != nullptr)
array<Byte>^data = System::Text::Encoding::ASCII->GetBytes(rdatastr);
stream->Write( data, 0, data->Length );
// 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..

Answer Source

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