-
-
Save adlrocha/20b9abacbd7423bbf5ce56a5fa63a7b4 to your computer and use it in GitHub Desktop.
Linear memory WASM
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; | |
use std::os::raw::c_void; | |
use std::slice; | |
use std::str; | |
use std::ptr::copy; | |
/* | |
Allocate a chunk of memory of `size` bytes in wasm module | |
*/ | |
#[no_mangle] | |
pub extern "C" fn alloc(size: usize) -> *mut c_void { | |
let mut buf = Vec::with_capacity(size); | |
let ptr = buf.as_mut_ptr(); | |
mem::forget(buf); | |
return ptr as *mut c_void; | |
} | |
#[no_mangle] | |
pub extern fn append(data_ptr: *mut c_void, size: u32) -> i32 { | |
let slice = unsafe { slice::from_raw_parts(data_ptr as _, size as _) }; | |
let in_str = str::from_utf8(&slice).unwrap(); | |
let mut out_str = String::new(); | |
out_str += in_str; | |
out_str += "<---- This is your string"; | |
unsafe { | |
copy(out_str.as_ptr(), data_ptr as *mut u8, out_str.len()) | |
}; | |
out_str.len() as i32 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment