wasm-micro-runtime
wasm-micro-runtime copied to clipboard
How do I access the memory as a byte array?
Hello,
I was wondering if anyone is aware of how to access the memory as a byte array from the wasm_exec_env_t in C?
I have seen someone do it in wasmer/wasi and javascript like this:
let bytes = new Uint8Array(instance.exports.memory.buffer);
Thanks for any help in advance.
If coding internal has to access WASMModuleInstance
first, then WASMMemoryInstance
is the target.
If coding in host functions, need to
- export the memory
- access the memory data with a Wasm C API named
wasm_memory_data()
Thank you. I am stuck on how to get the wasm_memory_t* pointer that is used internally from the wasm_module_inst_t.
wasm_memory_xxx
is partial of wasm-c-api. Should follow the declarations in the header [https://github.com/bytecodealliance/wasm-micro-runtime/blob/main/core/iwasm/include/wasm_c_api.h]. Better not hack wasm_module_inst_t
.
Btw, there is an example.
Thanks! I was wondering if it is possible to initialize a wasm runtime with the memory from a wasm_instance_t? If I initialize a wasm runtime I am using the wasm_module_inst_t but then I do not have the pointer to the wasm_memory_t like I have with the wasm_instance_t.
@jakob999999 A possible method to access the memory from exec_env:
wasm_module_inst_t module_inst;
uint32 app_start_offset, app_end_offset;
void *mem_start_addr, *mem_end_addr;
module_inst = wasm_runtime_get_module_inst(exec_env);
/* Use offset 0 to get the begin/end offset of wasm app */
ret = wasm_runtime_get_app_addr_range(module_inst, 0, &app_start_offset, &app_end_offset);
if (!ret) { return error; }
/* Convert app_start_offset/app_end_offset to native address */
mem_start_addr = wasm_runtime_addr_app_to_native(module_inst, app_start_offset);
mem_end_addr = wasm_runtime_addr_app_to_native(module_inst, app_end_offset);
And note that native address of linear memory may be changed after opcode memory.grow is executed, had better get the start/end address each time before accessing the linear memory.