add test.ts
This commit is contained in:
30
deno_test_wasm/test.ts
Normal file
30
deno_test_wasm/test.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
const wasmCode = await Deno.readFile("./test_wasm/target/wasm32-unknown-unknown/debug/test_wasm.wasm");
|
||||||
|
const wasmModule = new WebAssembly.Module(wasmCode);
|
||||||
|
const wasmInstance = new WebAssembly.Instance(wasmModule);
|
||||||
|
|
||||||
|
const linearMemory = wasmInstance.exports.memory;
|
||||||
|
|
||||||
|
function writeString() {
|
||||||
|
let s = "hello world !";
|
||||||
|
let encoded = new TextEncoder().encode(s);
|
||||||
|
let ptr = wasmInstance.exports.malloc(encoded.length);
|
||||||
|
const mem = new Uint8Array(linearMemory.buffer, ptr);
|
||||||
|
for (let i = 0; i < encoded.length; i++) {
|
||||||
|
mem[i] = encoded[i];
|
||||||
|
}
|
||||||
|
return ptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// from https://tilman.xyz/blog/2019/12/building-webassembly-for-deno/
|
||||||
|
function readString(memory, ptr) {
|
||||||
|
const mem = new Uint8Array(memory.buffer, ptr);
|
||||||
|
let length;
|
||||||
|
for (length = 0; mem[length] !== 0; length ++);
|
||||||
|
return new TextDecoder("utf-8").decode(new Uint8Array(mem.buffer, ptr, length));
|
||||||
|
}
|
||||||
|
|
||||||
|
let ptr = writeString();
|
||||||
|
console.log("DECODED:\n" + readString(linearMemory, ptr) + " @" + ptr);
|
||||||
|
|
||||||
|
let ptr2 = wasmInstance.exports.to_uppercase(ptr);
|
||||||
|
console.log("DECODED:\n" + readString(linearMemory, ptr2) + " @" + ptr2);
|
||||||
1
deno_test_wasm/test_wasm/build.sh
Normal file
1
deno_test_wasm/test_wasm/build.sh
Normal file
@@ -0,0 +1 @@
|
|||||||
|
cargo build --target wasm32-unknown-unknown
|
||||||
@@ -7,6 +7,7 @@ pub extern "C" fn malloc(len: usize) -> *mut c_char {
|
|||||||
s.into_raw()
|
s.into_raw()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
pub extern "C" fn to_uppercase(ptr: *mut c_char) -> *mut c_char {
|
pub extern "C" fn to_uppercase(ptr: *mut c_char) -> *mut c_char {
|
||||||
let s = unsafe { CString::from_raw(ptr) };
|
let s = unsafe { CString::from_raw(ptr) };
|
||||||
let s2 = CString::new(s.to_string_lossy().to_uppercase()).unwrap();
|
let s2 = CString::new(s.to_string_lossy().to_uppercase()).unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user