Hello Team! Thanks for the awesome support for was...
# webassembly
b
Hello Team! Thanks for the awesome support for wasm target. I am trying to allocate memory in Kotlin and return the pointer back to the host for it to set bytes of the serialised data I want to transfer to the module. Right now by what I have read on forum mainly here: https://discuss.kotlinlang.org/t/how-to-pass-rich-data-from-a-wasm-host-to-a-kotlin-guest/29527/3, it seems that allocated memory would be collected as soon as function returns. Is there no workaround to somehow
pin
the allocation until host sets the data and kotlin collects the bytes and then
unpin
the allocation ?
i
There is no pinned memory areas because linear memory allocator is...linear :) so it works like a stack and cannot do pin. You could wrap your main function with withScopedMemoryAllocator instead and allocate memory with this allocator but be aware about memory leaks.
d
Can you elaborate a little? Are you trying to have your host call an exported Kotlin function? And you want your exported Kotlin function to return a pointer to linear memory? If I’m understanding correctly, you are correct: that is not safe as the memory will get collected when you leave the withScopedMemoryAllocator() lambda. A few people have suggested an alternative which is to Import a host function which can receive your data. For example, setReturnValue(ptr). Now, in your exported function, instead of returning the pointer, you can pass the pointer to the imported function so your host can safely copy the data out of linear memory. Example: (Kotlin-esque)
Copy code
@WasmImport
SetReturnValue(pointer)

@WasmExport
YourFn() {
  let value = …
  withScopedMemoryAllocator(allocator {
   let pointer = allocator.allocate(10)
  pointer.write(value.toByte())
  //safely pass data to native
   SetReturnValue(pointer.address)
}
 // It would not be safe to use pointer out here since the memory has been collected. 
}
👍 1
b
yes @Daniel you are correct, that's what i want actually. And I believe the solution you provided is kinda the same which is given in the above link. So I guess that's the way I would have to interact with host it seems. Actually my constraint was that I can't change the imports host provides so I was searching for returning pointer outside the function