How do I free a piece of memory which has it’s own...
# kotlin-native
k
How do I free a piece of memory which has it’s own custom free function written in C and its lifetime is tied to the lifetime of a K/N object? I don’t think
memScope
would work for this, but I’m unsure
n
Use the free function from the C library that is being used.
k
How would you manage it for an allocation which is tightly coupled to a K/N object? eg.
Copy code
class KotlinNativeObject {
  val myCinteropAllocation = AllocateSomeStruct()
}

// cinterop
void FreeSomeStruct(SomeStruct* stuct)
Ideally, I’d like to automatically free
myCinteropAllocation
when its enclosing class gets garbage collected. That’s effectively a finalizer, though, and those are bad…… I’m wondering how other people have coped with this situation.
n
Kotlin Native doesn't support finalizers but the Closable pattern can be used. Unfortunately the Kotlin Standard library doesn't have the Closable interface but it is very easy to roll your own, eg:
Copy code
interface Closable {
  fun close()
}
The class doing the allocation would implement the Closable interface, and have its resource cleanup take place in the close function. Note that the Closable pattern is the same pattern used by many Kotlin JVM, Kotlin JS, and Kotlin Native libraries.
k
Yup, I figured that was the route I was going to need to take. Thanks.
u
Kotlin Native doesn't support finalizers but the Closable pattern can be used. Unfortunately the Kotlin Standard library doesn't have the Closable interface but it is very easy to roll your own, eg:
Copy code
interface Closable {
  fun close()
}
when is the close function be called?
k
usually, you scope the closable somehow. Eg, the
use
function.
Copy code
fun Closeable.use(block: () -> Unit) {
  try {
    block()
  } finally {
    close()
  }
}