Created
December 2, 2017 18:18
-
-
Save alanhoff/b256d8a4746e982d7854877722761fc3 to your computer and use it in GitHub Desktop.
Rust and WebAssembly error
This file contains hidden or 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
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