Skip to content

Instantly share code, notes, and snippets.

@adlrocha
Created December 13, 2020 14:55
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 adlrocha/20b9abacbd7423bbf5ce56a5fa63a7b4 to your computer and use it in GitHub Desktop.
Save adlrocha/20b9abacbd7423bbf5ce56a5fa63a7b4 to your computer and use it in GitHub Desktop.
Linear memory WASM
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