Alexey Zolotarev
01/07/2025, 10:31 AMwit-bindgen (kotlin branch) generated bindings work (InternalW.kt file):
@WasmExport("cm:example/iface#markdown-to-html")
fun __wasm_export_markdownToHtml(p0: Int, p1: Int): Int {
freeAllComponentModelReallocAllocatedMemory()
withScopedMemoryAllocator { allocator ->
val result: String = IfaceExportsImpl.markdownToHtml(STRING_FROM_MEM(p0, p1))
val ptr = /* RETURN_ADDRESS_ALLOC(size=8, align=4)*/ allocator.allocate(8).address.toInt()
val bytearray = result.encodeToByteArray()
val len = bytearray.size
val ptr0 = allocator.writeToLinearMemory(bytearray).address.toInt()
(ptr + 4).ptr.storeInt(len)
(ptr + 0).ptr.storeInt(ptr0)
return ptr
}
}
Specifically I would be grateful if you could explain
1. How would the function caller be able to write the argument data at the specified pointers (p0, p1) outside of the withScopedMemoryAllocator and how the data could be read by STRING_FROM_MEM which is executed within the newly created withScopedMemoryAllocator block which supposedly should work over a clean memory block?
2. The function returns a pointer ( ptr ) but when the function completes, the withScopedMemoryAllocator block completes too and as far as I can remember, the data allocated within it should be deallocated so isn't the ptr supposed to become invalid by the time the function returns? As far as I can understand from the Component Model spec, component-level value types are not exchanged using a shared memory so how would another component read the data produced by __wasm_export_markdownToHtml in this example?
Does withScopedMemoryAllocator work differently with component model?Svyatoslav Kuzmich [JB]
01/07/2025, 11:15 AMwithScopedMemoryAllocator implementation detail. Going out of withScopedMemoryAllocator scope doesn’t actually do anything with the memory (until new memory is allocated).
Component model calls this function. It makes a copy of the data returned in memory and forgets about our allocated memory before it can get corrupted by other allocations.Svyatoslav Kuzmich [JB]
01/07/2025, 11:26 AMfreeAllComponentModelReallocAllocatedMemory() should be done after STRING_FROM_MEM, but it happens to work correctly for because freeAllComponentModelReallocAllocatedMemory doesn’t do anything with the memory.Alexey Zolotarev
01/07/2025, 11:36 AMfreeAllComponentModelReallocAllocatedMemory come from? I don't have it available when importing the project even when using the latest Kotlin 2.1.0Svyatoslav Kuzmich [JB]
01/07/2025, 11:39 AMfreeAllComponentModelReallocAllocatedMemory comes from skuzmich/cm-prototype Kotlin branch.Svyatoslav Kuzmich [JB]
01/07/2025, 11:45 AM