0

Currently I'm trying to send values bigger than i8 from JS through wasm-memory to Rust like so:

Rust:

// CREATE WASM MEMORY FOR RUST AND JS DIRECT USE.
const WASM_MEMORY_BUFFER_SIZE: usize = 2; // 2 SLOTS
static mut WASM_MEMORY_BUFFER: [u8; WASM_MEMORY_BUFFER_SIZE] = [0; WASM_MEMORY_BUFFER_SIZE]; // INITIALIZE WITH 0

#[wasm_bindgen] // FOR JS TO GET THE POINTER TO MEMORY
pub fn get_wasm_memory_buffer_pointer() -> *const u8 {
  let pointer: *const u8;
  unsafe {
    pointer = WASM_MEMORY_BUFFER.as_ptr();
  }
  return pointer;
}

(^ Adjusting all the u8's to u16, u32 .. works fine in Rust)

JS:

// IMPORT THE GENERATED JS MODULE
import init from "../pkg/tem.js";

// GET WASM
const runWasm = async () => {
  const rustWasm = await init("../pkg/tem_bg.wasm");
  
  // CREATE THE WASM MEMORY
  var wasmMemory = new Uint8Array(rustWasm.memory.buffer);
  console.log("wasmMemory", wasmMemory);
  
  // GET THE POINTER TO WASM MEMORY FROM RUST
  var mem_pointer = rustWasm.get_wasm_memory_buffer_pointer();
  wasmMemory[mem_pointer] =  "i8";
};
runWasm();

The problem is that an i8 is quite small, and would need to send bigger numbers through memory.

I can adjust the u8 to f.e. u32 in Rust, than set a value: WASM_MEMORY_BUFFER[0] = "i32"; Getting the pointer as an i32 in JS with the Rust funcion is also still possible.

However, in JS I cannot change var wasmMemory = new Uint8Array(rustWasm.memory.buffer); to Uint32Array();. Thus, unlike Rust, setting a value: wasmMemory[mem_pointer] = "i32"; doesn't work.

Can this be resolved? Since I would like to set a value bigger than i8 in JS and read that value in Rust.

23rfew
  • 31
  • 8
  • Is the problem that you don't know how to write bigger values into the Uint8Array on the JS side or you don't know how to read bigger values from the buffer on the Rust side? – kelsny Aug 25 '22 at 19:04
  • If `Uint32Array` isn't possible, you can split a larger int into bytes? – Sedat Kapanoglu Aug 25 '22 at 19:04
  • -The problem is; I don't know how to write bigger values into the Uint8Array on the JS side. -Tbh I'm not sure how to split larger ints into bytes, but I can look into that. – 23rfew Aug 25 '22 at 19:07
  • 1
    If you look at [i32 to u8 array in Rust](https://stackoverflow.com/questions/29445026/converting-number-primitives-i32-f64-etc-to-byte-representations), you can probably figure out how to do it in JS (because it's the same format). Also have a read on [integer to byte array in JS](https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back). Be careful with the endianness. – kelsny Aug 25 '22 at 19:18
  • Thanks, the link will help a lot! l'll look into it. And I don't even know what endianness means so I got some work to do but I know more already haha – 23rfew Aug 25 '22 at 19:27

0 Answers0