Stream: wasmtime

Topic: wasmtime ruby memory by pointer


view this post on Zulip Noah Everett (Nov 28 2023 at 16:52):

Can you access the WASM memory by pointer instead of just offset/length via memory.read/write in Ruby?

view this post on Zulip Alex Crichton (Nov 28 2023 at 17:07):

cc @Saúl Cabrera

view this post on Zulip Noah Everett (Nov 28 2023 at 17:22):

Thanks @Alex Crichton ! The WASM code is allocating a buffer which returns a pointer back to the host to write to:

fun allocateBuffer(size : Int32) : Pointer(UInt8)
  ptr = Pointer(UInt8).malloc(size)
end

I was previously using Wasmer which allows something like:

    bufPtr = instance.exports.allocateBuffer.(100)
    $memory = instance.export("memory")
    view = $memory.uint8_view bufPtr

But maybe there is a better way to do this using Wasmtime's read/write methods, just not for sure how to access the "memory" in my WASM code which is written in Crystal lang which is why the previous code was using pointers.

Any help is greatly appreciated!

view this post on Zulip Alex Crichton (Nov 28 2023 at 17:24):

oh sorry I know very little about Ruby bindings myself, but I think Saul should know more

view this post on Zulip Noah Everett (Nov 28 2023 at 17:25):

No prob! just putting the relevant code here just in case, I appreciate the cc :)

view this post on Zulip Noah Everett (Nov 28 2023 at 20:00):

Hmm so I found "to_memory_view" but unsure how to use it in this context. Basically trying to figure out how to pass string data between the host and guest using an allocated buffer and pointer

or any other way to do this correctly in wasmtime-ruby

Thanks in advance for any direction!

view this post on Zulip Saúl Cabrera (Nov 28 2023 at 20:24):

Hi @Noah Everett -- if I'm understanding your question correctly, I think that you could achieve what you want by doing something like:

ptr  = instance.invoke("allocateBuffer",  100)
memory = instance.exports["memory"].to_memory
memory.write(ptr, <data>)
# use memory.read if needed

That said -- the bindings don't currently expose an API analogous to Memory::data_ptrhttps://docs.wasmtime.dev/api/wasmtime/struct.Memory.html#method.data_ptr, which could be another avenue to getting a mutable pointer to the memory

view this post on Zulip Noah Everett (Nov 28 2023 at 20:33):

@Saul Shanabrook oh wow I didn't know it could take a pointer (feel a little stupid now)! I just assumed it was just writing at the byte offset...trying it now, thank you!

view this post on Zulip Noah Everett (Nov 28 2023 at 20:37):

@Saúl Cabrera yup it works, I was making that way more complicated than it had to be, my fault...I really appreciate your help on the func_new and now this...cheers!


Last updated: Oct 23 2024 at 20:03 UTC