Skip to content

Instantly share code, notes, and snippets.

@thomas-jeepe
Last active June 11, 2022 01:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomas-jeepe/ff938fe2eff616f7bbe4bd3dca91a550 to your computer and use it in GitHub Desktop.
Save thomas-jeepe/ff938fe2eff616f7bbe4bd3dca91a550 to your computer and use it in GitHub Desktop.
<html>
<head>
<script>
var Module = {
wasmBinaryFile: "site.wasm",
onRuntimeInitialized: main,
};
function run_with_ptr(vec_ptr, cb) {
const ptr = Module.HEAPU32[vec_ptr / 4];
const len = Module.HEAPU32[vec_ptr / 4 + 1];
cb(Module.HEAPU8.subarray(ptr, ptr + len));
Module._drop_bytes(ptr);
}
function main() {
run_with_ptr(Module._bytes(), arr => {
console.assert(arr[0] == 1);
console.assert(arr[1] == 2);
console.assert(arr[2] == 3);
console.assert(arr.length == 3);
console.log("Woo: ", arr);
})
}
</script>
<script src="site.js"></script>
</head>
<body></body>
</html>
use std::mem;
#[repr(C)]
#[derive(Debug)]
pub struct JsBytes {
ptr: u32,
len: u32,
cap: u32,
}
impl JsBytes {
pub fn new(mut bytes: Vec<u8>) -> *mut JsBytes {
let ptr = bytes.as_mut_ptr() as u32;
let len = bytes.len() as u32;
let cap = bytes.capacity() as u32;
mem::forget(bytes);
let boxed = Box::new(JsBytes { ptr, len, cap });
Box::into_raw(boxed)
}
}
#[no_mangle]
pub fn drop_bytes(ptr: *mut JsBytes) {
unsafe {
let boxed: Box<JsBytes> = Box::from_raw(ptr);
Vec::from_raw_parts(boxed.ptr as *mut u8, boxed.len as usize, boxed.cap as usize);
}
}
fn returns_vec() -> Vec<u8> {
vec![1, 2, 3]
}
#[no_mangle]
pub fn bytes() -> *mut JsBytes {
JsBytes::new(returns_vec())
}
pub fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment