-
-
Save adlrocha/69719141cc07a4c01f1a6b3ffd668e9c to your computer and use it in GitHub Desktop.
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 anyhow::Result; | |
use wasmtime::*; | |
use std::ptr::copy; | |
fn main() -> Result<()> { | |
// Create our `Store` context and then compile a module and create an | |
// instance from the compiled module all in one go. | |
let wasmtime_store = Store::default(); | |
// Load Wasm module | |
let module = Module::from_file(wasmtime_store.engine(), "../modules/memory.wasm")?; | |
let instance = Instance::new(&wasmtime_store, &module, &[])?; | |
// Expose alloc function from Wasm module | |
let alloc = instance | |
.get_func("alloc") | |
.ok_or(anyhow::format_err!("failed to find `alloc` export"))? | |
.get1::<i32, i32>()?; | |
// Get linear memory | |
let memory = instance | |
.get_memory("memory") | |
.ok_or(anyhow::format_err!("failed to find `memory` export"))?; | |
// Input string | |
let text = String::from("The input string"); | |
let size = text.len() as i32; | |
// Allocate memory and visualize it. | |
let mem_ptr = alloc(size+30)?; | |
println!("Pointer received {:#x}, {}", mem_ptr, size); | |
println!("Host memory pointer {:#x?}", memory.data_ptr()); | |
println!("wasm allocated memory {:#x?}", | |
unsafe{ memory.data_unchecked_mut().as_ptr() }); | |
let pointer = unsafe { memory.data_ptr().add(mem_ptr as usize) }; | |
println!("address for wasm object in rust: {:#x?}", pointer); | |
// Copy input data in linear memory- | |
unsafe { | |
let bytes = text.as_bytes(); | |
copy(bytes.as_ptr(), | |
pointer, | |
bytes.len()); | |
} | |
// Expose append function from wasm module | |
let append = instance | |
.get_func("append") | |
.ok_or(anyhow::format_err!("failed to find `append` export"))? | |
.get2::<i32, i32, i32>()?; | |
// Execute function | |
let new_size = append(mem_ptr, size)?; | |
println!("New Size received: {}", new_size); | |
// Get output data | |
let byte3 = unsafe { | |
String::from_utf8(memory.data_unchecked()[mem_ptr as usize..][..new_size as usize] | |
.to_vec()).unwrap() | |
}; | |
println!("Result: {}", byte3); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment