开发者

Can you UTF8Encode a System::String^ to a Byte*? [duplicate]

开发者 https://www.devze.com 2023-03-04 05:34 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Whats the diffrence between an array<Byte>^ and a byte*?
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消