Pass a pointer string as an argument in host import function in Rust WebAassembly (wasmtime)

1k views Asked by At

so I have the following import in my generated .wast file (disclaimer: I have not written the wasm file myself):

 (import "index" "bigDecimal.fromString" (func $fimport$1 (param i32) (result i32)))

and I need to write up the host import function in Rust. I cannot use &str in Rust but also the import requires an i32. I'm guessing I need to pass a pointer to a string, defined in Rust? Can anyone point me to the right direction? Some example of that being done in wasmtime?

let from_string = Func::wrap(&store, |a: i32| {
    println!("a={}", a);
});

Thanks a ton in advance!

1

There are 1 answers

0
timog On

You are right, the parameter a is a pointer to the string inside of the Wasm modules memory. You can access this via wasmtime::Memory::data_ptr(...) function. To get the memory from the caller you can add a parameter of type wasmtime::Caller to your closure. This parameter must not be in your wasm modules function signature but only in the host functions signature.

I hope this short example will help:

let read_wasm_string_func = Func::wrap(&store, |mut caller: Caller<'_, WasiCtx>, ptr_wasm: i32| -> i32 {
    let memory = caller.get_export("memory").unwrap().into_memory().unwrap();
    unsafe {
        let ptr_native = memory.data_ptr(&caller).offset(ptr_wasm as isize);
        // Do something with the pointer to turn it into a number
        // return int
        return num;
    }
});