Possible Duplicate:
Whats the diffrence between an array<Byte>^ and a byte*?
i am translating some c# code to c++ however translating the piece about UTF8Encoding, i get stuck that c++ returns a array^ while i need a byte* as areturn type. I spend a long time on this code trying to get around it but i keep failing. How could i change it to return a byte*?
array<Byte>^ StrToByteArray(System::String^ unicodeString)
{
UTF8Encoding^ utf8 = gcnew UTF8Encoding;
array<Byte>^ encodedBytes = utf8->GetBytes( unicodeStri开发者_如何学编程ng );
return encodedBytes;
}
I think there is no way to do a conversion from array to X* without manually copying each element. This would look something like following snippet:
byte* StrToByteArray(System::String^ unicodeString)
{
UTF8Encoding^ utf8 = gcnew UTF8Encoding;
array<Byte>^ encodedBytes = utf8->GetBytes( unicodeString );
const size_t len = encodedBytes->Length;
byte* encodedBytesRaw = new byte[len+1];
for( int i=0; i<len; ++i )
encodedBytesRaw[i] = encodedBytes[i];
encodedBytesRaw [len]=0;
return encodedBytesRaw;
}
The caller has to delete the returned byte array, once he is finished with it.
精彩评论