Are there any examples out there of wrapping a cpp...
# multiplatform
b
Are there any examples out there of wrapping a cpp object and properly calling a cpp destructor when the kotlin object wrapping it is destroyed?
s
Kotlin can’t call cpp libraries without a C wrapper around the library.
b
Is there generally a way to tie memory lifetime from C to that of a Kotlin object?
d
Nope, they have to be manually destroyed. There's no sense of a destructor.
b
👍 thanks!
o
To be precise, there’s no user-controlled way to bind cleanup routine to Kotlin object. Control Kotlin object lifetime from C can be achieved by creating StableRef.
b
@olonho thanks! Specifically, we're trying figure out if there's a way to use a lock that's not a spin lock on Windows, but doing so requires knowing when we should cleanup the lock
o
object lifetime bound resources (such a Windows lock) doesn’t look like a great idea in general, use some scope bound resource control instead
👍 2
b
@olonho here's an example where such a scope-bound resource isn't practical: https://github.com/touchlab/Stately/pull/6
Until there's some way to get a deinit/destructor callback in Kotlin, we won't be able to use more efficient locks on other platforms. Seems like stdlib could benefit as well: https://github.com/JetBrains/kotlin-native/blob/f47fe79ef804a3a3f8a86989b767a56b2f7874c9/runtime/src/main/kotlin/kotlin/native/concurrent/Lock.kt
o
Not sure why this PR manifests that scope-bound locks are insufficient. See how https://github.com/JetBrains/kotlin-native/blob/9d70ec0dbb21a4eea4db902218ed9a81940e0617/samples/videoplayer/src/videoPlayerMain/kotlin/Disposable.kt#L33 is used around videoplayer sample to solve similar problem.
b
@olonho i see. so not scope-bound necessarily (scope-bound to me makes me think of
memScoped {}
), but we should come up with a way to manually dispose of the lock/resource when we're done with it?
o
Yeah, let's call it logical scope, essentially predefined program execution fragment with clear boundaries
👍 1
b
This does essentially force some resources back into the "free-it-yourself" style of mem management though, which is not great. It also feels a bit weird that you have to do this in the native world, unless you're running on iOS/macOS, where lock objects bridge for free
o
Nope, it’s not “free-it-yourself”, more like “think-over-program-behavior-yourself”. Binding resource mgmt to memory mgmt is pretty old anti-pattern of computer engineering, with well-known fundamental problems. With first-class functions, suspend functions and inline functions available in Kotlin one can think over composition rules so that there’s explicit resource consumption control.
b
👍 that's reasonable