memory stuff

This commit is contained in:
Greg Shuflin 2023-11-19 02:00:38 -08:00
parent 0633ad4b9a
commit 5dfd4b4687
2 changed files with 45 additions and 0 deletions

View File

@ -6,6 +6,21 @@ const runWasm = async () => {
const result = rustWasm.de_iavascriptis(0, 1); const result = rustWasm.de_iavascriptis(0, 1);
console.log("Should be undefined: ", rustWasm.add_integer_with_constant); console.log("Should be undefined: ", rustWasm.add_integer_with_constant);
document.body.textContent = `Gamarjoba! result: ${result}`; 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(); runWasm();

View File

@ -15,3 +15,33 @@ const CONSTANT: i32 = 94;
fn add_integer_with_constant(a: i32, b: i32) -> i32 { fn add_integer_with_constant(a: i32, b: i32) -> i32 {
a + b + CONSTANT 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
}