Skip to content

Instantly share code, notes, and snippets.

@alanhoff
Created December 2, 2017 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanhoff/b256d8a4746e982d7854877722761fc3 to your computer and use it in GitHub Desktop.
Save alanhoff/b256d8a4746e982d7854877722761fc3 to your computer and use it in GitHub Desktop.
Rust and WebAssembly error
const rust = require('rustify');
const wasm = rust`
use std::ffi::{CString};
use std::os::raw::{c_char};
#[no_mangle]
pub extern "C" fn str_len(ptr: *mut c_char) -> usize {
unsafe {
let string = CString::from_raw(ptr);
string.to_bytes().len()
}
}
#[no_mangle]
pub extern "C" fn hello_world() -> *mut i8 {
CString::new("Hello World!").unwrap().into_raw()
}
`
function ptrToString(buffer, ptr, length) {
const bytes = new Uint8Array(buffer, ptr, length);
return new TextDecoder('utf8').decode(bytes);
}
WebAssembly.instantiate(wasm, {})
.then(res => {
const {str_len, hello_world, memory} = res.instance.exports;
const hello_ptr = hello_world();
const hello_len = str_len(hello_ptr);
console.log(ptrToString(memory.buffer, hello_ptr, hello_len));
// expected "Hello World!" got "ello World!"
}).catch(e => {
console.error('Creating WASM module failed', e)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment