diff --git a/index.js b/index.js index 24fd012..5410707 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,21 @@ const runWasm = async () => { const result = rustWasm.de_iavascriptis(0, 1); console.log("Should be undefined: ", rustWasm.add_integer_with_constant); document.body.textContent = `Gamarjoba! result: ${result}`; + + const NUMBER = 257; + + console.log("Write in WASM, read in JS"); + rustWasm.store_value_in_wasm_mem_idx_0(NUMBER); + let wasmMemory = new Uint8Array(rustWasm.memory.buffer); + let ptr = rustWasm.get_wasm_mem_buffer_pointer(); + console.log("Pointer from rust: ", ptr); + + console.log(wasmMemory[ptr+0]); // should be NUMBER, wrapped around 256 + + console.log("Write in JS, read in wasm"); + wasmMemory[ptr+1] = 15; + console.log(rustWasm.read_wasm_mem_buffer_idx_1()); // should be 15 + }; runWasm(); diff --git a/src/lib.rs b/src/lib.rs index d1ebca2..458c246 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,3 +15,33 @@ const CONSTANT: i32 = 94; fn add_integer_with_constant(a: i32, b: i32) -> i32 { a + b + CONSTANT } + +// Linear memory example - see +// https://wasmbyexample.dev/examples/webassembly-linear-memory/webassembly-linear-memory.rust.en-us.html + +const WASM_MEMORY_BUF_SIZE: usize = 2; +static mut WASM_MEMORY_BUFFER: [u8; WASM_MEMORY_BUF_SIZE] = [0; WASM_MEMORY_BUF_SIZE]; + +#[wasm_bindgen] +pub fn store_value_in_wasm_mem_idx_0(value: u8) { + unsafe { + WASM_MEMORY_BUFFER[0] = value; + } +} + +#[wasm_bindgen] +pub fn get_wasm_mem_buffer_pointer() -> *const u8 { + let ptr: * const u8 = unsafe { + WASM_MEMORY_BUFFER.as_ptr() + }; + ptr +} + + +#[wasm_bindgen] +pub fn read_wasm_mem_buffer_idx_1() -> u8 { + let value = unsafe { + WASM_MEMORY_BUFFER[1] + }; + value +}