How do I convert a fixed byte array to a String in managed c++/cli ?
For example I have the following Byte array.
Byte byte_data[5];
byte_data[0]='a';
byte_data[1]='b';
byte_data[2]='c';
byte_data[3]='d';
byte_data[4]='e';
I have tried the following code
String ^mytext=System::Text::UTF8Encoding::UTF8->GetString(byte_data);
I get the following error:
error C2664: 'System::String ^System::Text::Encoding::GetString(cli::array<Type,dimension> ^)' : cannot convert parameter 1 from 'unsigned char [5]' to 'cli::array<Type,dimension> ^'
Arm yourself with some knowledge about casting between pointers to signed and unsigned types and then you should be set to use String::String(SByte*, Int32, Int32)
. It might also pay to read the Remarks on the page, specifically around encoding.
I've reproduced the sample from the page here:
// Null terminated ASCII characters in a simple char array
char charArray3[4] = {0x41,0x42,0x43,0x00};
char * pstr3 = &charArray3[ 0 ];
String^ szAsciiUpper = gcnew String( pstr3 );
char charArray4[4] = {0x61,0x62,0x63,0x00};
char * pstr4 = &charArray4[ 0 ];
String^ szAsciiLower = gcnew String( pstr4,0,sizeof(charArray4) );
// Prints "ABC abc"
Console::WriteLine( String::Concat( szAsciiUpper, " ", szAsciiLower ) );
// Compare Strings - the result is true
Console::WriteLine( String::Concat( "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper->ToUpper(), szAsciiLower->ToUpper() ) ? (String^)"TRUE" : "FALSE") ) );
// This is the effective equivalent of another Compare method, which ignores case
Console::WriteLine( String::Concat( "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper, szAsciiLower, true ) ? (String^)"TRUE" : "FALSE") ) );
Here is one option:
array<Byte>^ array_data = gcnew array<Byte>(5);
for(int i = 0; i < 5; i++)
array_data[i] = byte_data[i];
System::Text::UTF8Encoding::UTF8->GetString(array_data);
Not compiled but I think you get the idea.
Or use the String constructor, as indicated by @ta.speot.is, with encoding set to System.Text::UTF8Encoding
.
For those interested in another working solution. I used the notes of ta.speot.is and developed a working solution,You should be able to use this solution or that provided by Rasmus.
Byte byte_data[5];
byte_data[0]='a';
byte_data[1]='b';
byte_data[2]='c';
byte_data[3]='d';
byte_data[4]='e';
char *pstr3 = reinterpret_cast<char*>(byte_data);
String^ example1 = gcnew String( pstr3 );//Note: This method FAILS if the string is not null terminated
//After executing this line the string contains garbage on the end example1="abcde<IqMŸÖð"
String^ example2 = gcnew String( pstr3,0,sizeof(byte_data)); //String Example 2 correctly contains the expected string even if it isn't null terminated