简体   繁体   中英

What is the UTF8ToString equivalent for turning binary data to a Javascript array

I have C code which returns a void * and size_t length to Javascript running in a web worker. In Javascript i have the following

let start = getStartAddress();
let len = getLength();

I know for Strings i can do

let mystring = UTF8ToString(start);

This is documented https://emscripten.org/docs/api_reference/preamble.js.html#conversion-functions-strings-pointers-and-arrays

I am at a total loss as to how i get an Uint8Array that i can send through postMessage .

Where would i find documentation that tells me how to do that?

In the absence of documentation an answer to my question would suffice.

Ok, so i actually found the definition for UTF8ToString in the Javascript file the emscripten compiler created for my .wasm file. I thought it was a native function. It calls UTF8ArrayToString in the same javascript file. Learning from that source code i came up with the following.

function BytesToArray(base, len) {
  let out = new Array(len);
  let i = 0, ptr = base, end = base + len;
  while (ptr < end) {
    out[i] = HEAPU8[ptr];
    i++;
    ptr++;
  }
  return out;
}
let mydata = BytesToArray(start, len);
postMessage(mydata);

I hope the performance isn't too bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM