Last active
June 11, 2022 01:12
-
-
Save thomas-jeepe/ff938fe2eff616f7bbe4bd3dca91a550 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://stackoverflow.com/questions/45725975/getting-an-array-in-javascript-from-rust-compiled-to-emscripten