I want to create a byte vector ( Vec<u8>in Rust) and access it using JS like Arrayor Uint8Arrayand send it to WebSocket or to IndexedDB.
I found How to pass an array from JavaScript to Rust that was compiled using Emscripten? , which is the exact opposite of what I would like to do, but very relevant. Other than that, I know the type of the array in Emscripten, but I don't know how to use it correctly.
My best guess on how to do this is to try to return the vector as_mut_ptrand use a pointer to Module.HEAPU8.
main.rs
#[no_mangle]
pub fn bytes() -> *mut u8 {
vec![1, 2, 3].as_mut_ptr()
}
fn main() {}
The index.html part
var Module = {
wasmBinaryFile: "site.wasm",
onRuntimeInitialized: main,
};
function main() {
let ptr = Module._bytes();
console.log(ptr);
console.log(Module.HEAPU8.slice(ptr, ptr + 10));
console.log(Module.HEAPU8.subarray(ptr, ptr + 100));
let arr = Module.cwrap('bytes', 'array', []);
console.log(arr());
}
The console results ended as follows:
5260296 site:11:13
Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] site:12:13
Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90 more… ] site:13:13
5260296 site:15:13
, , -, . , , .
, , , Rust Vec<u8> ( bytes).
, Wasm Emscripten, Wasm.