Skip to content

Instantly share code, notes, and snippets.



Created Dec 2, 2017
What would you like to do?
Rust and WebAssembly error
const rust = require('rustify');
const wasm = rust`
use std::ffi::{CString};
use std::os::raw::{c_char};
pub extern "C" fn str_len(ptr: *mut c_char) -> usize {
unsafe {
let string = CString::from_raw(ptr);
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
You can’t perform that action at this time.