how do I allocate memory in wasm? `withScopedMemor...
# webassembly
s
how do I allocate memory in wasm?
withScopedMemoryAllocator {}
frees it up directly after executing the block so that doesn't work. Alternatively, is there a way to find out the memory address of a top level bytearray like
private val sharedBuffer = ByteArray(4096)
? I need to write a bytearray into memory and retrieve the pointer to return it back to the host
i
Hi, linear memory allocated with memory allocator and gc memory are totally different memory spaces, so no way to find a pointer to a gc object in linear memory in Wasm. The only way to work with the linear memory in Kotlin is to allocate it with memory allocator and copy gc array byte to byte and use it until memory allocator goes out of scope.
s
that's what I'm trying to do.
withScopedMemoryAllocator
does work for my experiments, I guess freeing up doesn't mean being immediately overwritten.
Copy code
withScopedMemoryAllocator {
    val bytes = Cbor.encodeToByteArray(Memo("Wasm", 1))
    val ptr = it.allocate(bytes.size)
    bytes.forEachIndexed { index, byte ->
        Pointer((ptr.address + index.toUInt())).storeByte(byte)
    }
    return pack(ptr.address, bytes.size)
}
I'm still a bit worried about inconsistency, I'm reading from memory that's already freed up. There is also
componentModelRealloc
which is only freed up manually, but for this I would need an initial pointer.
i
If you are using wasmJs you can use callbacks to workaround it or put needed data directly to js arrays.
s
I'm using wasmWasi and executing it in kotlin using chasm as the host runtime. eventually to work as plugins in a compose app
c
Version 1.4.7 of chasm is rolling out now with wasmjs support in the gradle plugin
🙏 1
s
It's still saying
Unresolved platforms: [wasmJs]
with version 1.4.7 🤔
c
Theres an example web project here if you need some steer. If you're trying to use the lower level virtual machine api that doesn't support wasmJs, its the plugin and the higher level virtual machine api that does.
s
I see. I do in fact need the lower level api, the wasm binaries are loaded dynamically. I assume I should use the js api directly for web targets
c
Its hard to say without knowing the use case but even the higher level vm abstraction (which does support wasmJs) has some ability to probe into wasm, read and write from memories etc. The full high level interface is here