withScopedMemoryAllocator

inline fun <T> withScopedMemoryAllocator(block: (allocator: MemoryAllocator) -> T): T(source)

Runs the block of code, providing it a temporary MemoryAllocator as an argument, and returns the result of this block.

Frees all memory allocated with the provided allocator after running the block.

This function is intened to facilitate the exchange of values with outside world through linear memory. For example:

val buffer_size = ...
withScopedMemoryAllocator { allocator ->
val buffer_address = allocator.allocate(buffer_size)
importedWasmFunctionThatWritesToBuffer(buffer_address, buffer_size)
return readDataFromBufferIntoManagedKotlinMemory(buffer_address, buffer_size)
}

WARNING! Addresses allocated inside the block function become invalid after exiting the function.

WARNING! A nested call to withScopedMemoryAllocator will temporarily disable the allocator from the outer scope for the duration of the call. Calling MemoryAllocator.allocate on a disabled allocator will throw IllegalStateException.

WARNING! Accessing the allocator outside of the block scope will throw IllegalStateException.

Since Kotlin

1.8
inline fun <T> withScopedMemoryAllocator(block: (allocator: MemoryAllocator) -> T): T(source)

Runs the block of code, providing it a temporary MemoryAllocator as an argument, and returns the result of this block.

Frees all memory allocated with the provided allocator after running the block.

This function is intened to facilitate the exchange of values with outside world through linear memory. For example:

val buffer_size = ...
withScopedMemoryAllocator { allocator ->
val buffer_address = allocator.allocate(buffer_size)
importedWasmFunctionThatWritesToBuffer(buffer_address, buffer_size)
return readDataFromBufferIntoManagedKotlinMemory(buffer_address, buffer_size)
}

WARNING! Addresses allocated inside the block function become invalid after exiting the function.

WARNING! A nested call to withScopedMemoryAllocator will temporarily disable the allocator from the outer scope for the duration of the call. Calling MemoryAllocator.allocate on a disabled allocator will throw IllegalStateException.

WARNING! Accessing the allocator outside of the block scope will throw IllegalStateException.

Since Kotlin

1.8