wasmerio / wasmer-rust-example

Example of WebAssembly embedding in Rust using Wasmer
https://wasmerio.github.io/wasmer/rust/wasmer_runtime/
162 stars 24 forks source link

Writing data to Wasmer VM #6

Closed ghost closed 5 years ago

ghost commented 5 years ago

How in wasmer-runtime to write data in memory of VM and to read them in wasm Rust? I know how to do this in JS, but I did not find the API in the wasmer-runtime to transfer the data. In the above code, I tried to read the data on stupid.

main.rs

...
static TEST_STR: &'static str = "Test string";
...
instance.call("str_wasm", &[Value::I32(TEST_STR.as_ptr() as i32), Value::I32(TEST_STR.len() as i32)])?;
...

lib.rs

...
#[no_mangle]
pub extern fn str_wasm(ptr: *mut u8, len: usize) {
    let slice: &[u8] = unsafe { slice::from_raw_parts(ptr, len) };
    let string = str::from_utf8(slice).unwrap();
    unsafe {
        print_str(string.as_ptr(), string.len());
    }
}
...

Well, it is clear that this is too simple. Here is the error: Error: CallError (Runtime (OutOfBoundsAccess {memory: MemoryIndex (0), addr: None}))

bjfish commented 5 years ago

You should write the string into the instance’s linear memory and pass the index to the memory as the pointer.
The memory view should have a set method to modify the bytes: https://github.com/wasmerio/wasmer/blob/master/lib/runtime-core/src/vm.rs#L142

Right now I think you are passing a rust pointer and the value is beyond the size of your memory.

ghost commented 5 years ago

@bjfish I do not understand you. Https://github.com/wasmerio/wasmer/blob/master/lib/runtime-core/src/vm.rs#L142 shows a read and not a write to memory. Any code examples?

bjfish commented 5 years ago

@Haski-server I've added an example here: https://github.com/wasmerio/wasmer-rust-example/commit/6a512a37c704ed0416f4b6100ab92b1347555161

This section shows how to write into the memory: https://github.com/wasmerio/wasmer-rust-example/commit/6a512a37c704ed0416f4b6100ab92b1347555161#diff-f9a17bdeda71648694af57037fea1d6dR39