Currently, I am working on a project which uses the wasmtime
(a wasm
runtime implemented by rust) to load and initiate some wasm
modules.
And I would like a wasm
module to access the global val. So I write some code:
extern "C" {
static offset: i32;
}
#[no_mangle]
pub extern "C" fn hello() -> i32 {
unsafe { offset }
}
And I use the command to compile it to wasm:
cargo build --target wasm32-unknown-unknown
Next, I write another rust program to load and initiate the wasm
module:
use wasmtime::*;
struct MyState {
count: i32,
}
fn main() -> Result<()> {
let engine = Engine::default();
let mut store = Store::new(&engine, MyState { count: 0 });
// the path is corrected.
let module = Module::from_file(&engine, "./src/linkerglobal.wasm")?;
let mut linker = Linker::new(&engine);
// create a global value
let ty = GlobalType::new(ValType::I32, Mutability::Var);
let my_global = Global::new(&mut store, ty, Val::I32(0x1234))?;
linker.define(&mut store, "host", "offset", my_global)?;
let instance = linker.instantiate(&mut store, &module)?;
let hello = instance.get_typed_func::<(), i32>(&mut store, "hello")?;
let res = hello.call(&mut store, ())?;
println!("res: {}", res); // it should be 0x1235
Ok(())
}
I think the output should be: res: 4660
, however, the output is res: 0
.
Can you help me? Thanks a lot