I have two very simple i/o extern functions in rust:
fn read(buf: *mut u8, count: usize, block: bool) -> isize;
fn write(buf: *const u8, count: usize) -> isize;
compiled to wasm32, and I would like to know how to get the data back from the cpp API:
wasmtime::Store store(*program->engine);
store.context().set_epoch_deadline(1);
wasmtime::Func read_fn = wasmtime::Func::wrap(
store,
[&store](int32_t pointer, uint32_t count) -> int32_t {
SDL_Log("Calling back...");
return 0;
});
wasmtime::Func write_fn = wasmtime::Func::wrap(
store,
[&store](const int32_t pointer, uint32_t count) -> int32_t {
SDL_Log("Calling back...");
return 0;
});
I notice Context#get_data
which may be what I am looking for and made me try
// Rust called
let mut value: i32 = 5;
value += 5;
unsafe {
write(&value as *const _ as *const u8, core::mem::size_of_val(&value) as usize);
}
// C++ reading
auto data_any = store.context().get_data();
auto data_ptr =
std::any_cast<uint8_t *>(data_any);
auto int_ptr = reinterpret_cast<int32_t *>(
data_ptr + pointer);
auto data_value = *int_ptr;
SDL_Log("Data at pointer: %d", data_value);
But I think I am worsening my case.
you'll want to capture a wasmtime::Memory
in your closures and access it. The pointer from .get_data()
is application-specific and you can also store data inside of it too.
Something like this?
wasmtime::Memory memory = std::get<wasmtime::Memory>( *instance.get(store, "memory"));
I understand what the name is supposed to be for a function, but a bit more confused in the case of memory. (is the name in the binary standardized?)
Also, how am I supposed to get it since the instance is created after the linker?
From the embedder perspective it's "just another export" and toolchains conventionally use memory
right now. Whether or not that changes depends on whether or not the toolchain you used to produce the module changes. For accessing it you'll probably need to store it in the get_data()
pointer after instantiation and then access it during the closure.
FWIW I'd recommend reading the Rust docs as they're similar to C++ in terms of functionality and should have examples for this.
Last updated: Feb 28 2025 at 02:27 UTC