views:

204

answers:

1

How to convert AS3 ByteArray into wchar_t const* filename?

So in my C code I have a function waiting for a file with void fun (wchar_t const* filename) how to send to that function my ByteArray? (Or, how should I re-write my function?)

+1  A: 

A four month old question. Better late than never?

To convert a ByteArray to a String in AS3, there are two ways depending on how the String was stored. Firstly, if you use writeUTF it will write an unsigned short representing the String's length first, then write out the string data. The string is easiest to recover this way. Here's how it's done in AS3:

byteArray.position = 0;
var str:String = byteArray.readUTF();

Alternatively, toString also works in this case. The second way to store is with writeUTFBytes. This won't write the length to the beginning, so you'll need to track it independantly somehow. It sounds like you want the entire ByteArray to be a single String, so you can use the ByteArray's length.

byteArray.position = 0;
var str:String = byteArray.readUTFBytes(byteArray.length);

Since you want to do this with Alchemy, you just need to convert the above code. Here's a conversion of the second example:

std::string batostr(AS3_Val byteArray) {
    AS3_SetS(byteArray, "position", AS3_Int(0));
    return AS3_StringValue(AS3_CallS("readUTFBytes", byteArray,
        AS3_Array("AS3ValType", AS3_GetS(byteArray, "length")) ));
}

This has a ridiculous amount of memory leaks, of course, since I'm not calling AS3_Release anywhere. I use a RAII wrapper for AS3_Val in my own code... for the sake of my sanity. As should you.

Anyway, the std::string my function returns will be UTF-8 multibyte. Any standard C++ technique for converting to wide characters should work from here. (search the site for endless reposts) I suggest leaving it is as it, though. I can't think of any advantage to using wide characters on this platform.

Gunslinger47
RAII wrapper... hm... could you provide any links?
Blender
@Jak: Make a class where one constructor takes a AS3_Val and stores it. Its copy constructor copies the other object's AS3_Val and calls `AS3_Acquire`. In the destructor it calls `AS3_Release`. That's the basic functionallity.
Gunslinger47