Hello Team, I'm working on a Kotlin Multiplatform...
# multiplatform
a
Hello Team, I'm working on a Kotlin Multiplatform project where we need to interface with native resources (specifically, C/C++ pointers) from the common code. We have Kotlin classes that hold references to these native pointers. In platforms like Swift and JVM, we can use
deinit
and
finalize
respectively to clean up these resources when the object is deallocated. However, in the common module of KMP, we don't have access to constructs like
PhantomReference
, nor do we have destructors or finalizers that we can rely on for automatic cleanup when the object is garbage collected. Currently we support: JS(wasm), iOS, Android, JVM TLDR: Is there an existing mechanism or recommended best practice in Kotlin Multiplatform for managing the cleanup of native resources held by objects in the common code?
o
However, in the common module of KMP, we don't have access to constructs like
PhantomReference
or
WeakReference
Would this help? https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1726162436336299
a
not exactly, looking for mechanism to schedule and trigger cleanup of native objects
l
@ar-g Are you looking for the
Cleaner
object?
Here's an example in my code where I deallocate a GMP object when the reference goes out of scope: https://codeberg.org/loke/array/src/branch/master/mpbignum/src/linuxMain/kotlin/com/dhsdevelopments/mpbignum/bigint-linux.kt#L31
a
thanks, this can be used for native part! was looking for generic api on all platforms though
o
I was tried to experiment with this not so long time ago. Platform APIs for this are available everywhere except for
wasm-wasi
you can take a look on code here: https://github.com/whyoleg/clozy/blob/main/clozy-core/src/commonMain/kotlin/SafeCloseable.kt Though, I haven't had time to finalize implementation 🙂
🙏 1
l
I'm not sure a generic API for this is that useful though, since the thing you normally want to do in the cleaner is to clean up native resources, and that cleanup is usually platform specific.
a
ahh right, in our case it's native objects stored in native heap in every platform
o
the thing you normally want to do in the cleaner is to clean up native resources
it's also could be used for leak-tracking. F.e if you have some closeable resource which you want to make sure that user closes (f.e TCP connection may be or some off-heap buffer, etc?) And so, if user haven't closed it, you can
close
it automatically and nudge users via logging: Hey, you haven't closed this, probably there is some bug out-there. AFAIK Netty has leak tracker based on
Cleaner
+ if we will have some kind of multiplatform FFI API - having KMP Cleaner-like API will also be useful
l
Fair enough. My project (linked above) does implement a multi-platform FFI that abstracts the Java 21 FFI as well as native Linux using libffi.
However, I move the responsibility of freeing resources to the user.