1

I have a u8[] array in WebAssembly code, how can I read it in regular JS? Calls to it just return me a i32.

// Load module WebAssembly.Instance
const instance = await getInstance("./build/embed.wasm");

// Try to get the array of bytes from the module
const embeddedFileBytes = Uint8Array.from(instance.fileBytes);

// write the file to disc
await writeFile("./output.text", embeddedFileBytes);

// check the hash is the same as the original file that was embedded
expect(sha1("./output.text")).toEqual(sha1("./input.text"))

The webassembly module has an export:

export const fileBytes: u8[] = [83,65,77,80,76,69,10];
4
  • Can you provide any sample code of your work? Otherwise I cannot show an example. Commented Jan 18, 2020 at 11:45
  • Added an example code thanks @BumsikKim Commented Jan 18, 2020 at 11:54
  • Thanks, but what is that WebAssembly module written in? And is it just a one-liner? Also what is getInstance()? It is not a standard WebAssembly API, so what kind of library you used for the JS code? Since you are already not using a "regular JS", please provide a more specific context... Commented Jan 18, 2020 at 11:59
  • 1
    Note that it is not just about WebAssembly anymore but a question about your framework for WebAssembly. So you probably want to add additional tags in your question. Commented Jan 18, 2020 at 12:08

1 Answer 1

2

WebAssembly is a low level virtual machine that only supports numeric types. More complex types, such as as strings, structs and arrays, are encoded within the WebAssembly's linear memory - which is a contiguous block of memory that both WebAssembly and JavaScript can read and write to.

The value returned by fileBytes isn't the array itself, it is instead a pointer to the location of the array in linear memory. In order to obtain the data from the array, you'll need to read it from linear memory - in much the same way as you would read a string, as described in the following question:

How can I return a JavaScript string from a WebAssembly function

If you don't want to write this 'glue' code yourself, I'd recommend looking into wasm-bindgen

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the penny droped and I understand now. I examned the 'glue' available in WebAssembly/binaryen and was able to find a method (__getUint8Array) to extract the bytes using their loader

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.