Big Chungus
03/14/2023, 5:07 PMLandry Norris
03/14/2023, 5:10 PMthis
) to a variable, and when the variable is GC’ed, it runs a lambda.Big Chungus
03/14/2023, 5:10 PMLandry Norris
03/14/2023, 5:11 PMBig Chungus
03/14/2023, 5:11 PMkevin.cianfarini
03/14/2023, 5:11 PMLandry Norris
03/14/2023, 5:13 PMthis
, you’re creating a reference to the this
object, which also holds the cleaner, so it can’t be GC’ed.Big Chungus
03/14/2023, 5:14 PMLandry Norris
03/14/2023, 5:18 PMclass FooFromCWrapper(val foo: CPointer<CFoo>) {
//val cleaner = createCleaner(foo) { c_lib_free(foo) } //will leak memory
val cleaner = createCleaner(foo) { c_lib_free(it) } //won't leak
}
Big Chungus
03/14/2023, 5:19 PMjw
03/14/2023, 5:19 PMLandry Norris
03/14/2023, 5:19 PMBig Chungus
03/14/2023, 5:22 PMLandry Norris
03/14/2023, 5:23 PMJeff Lockhart
03/14/2023, 5:51 PMclass CWrapper(
val foo: CPointer<CFoo>,
val bar: CPointer<CBar>
) {
val memory = object {
val foo = foo
val bar = bar
}
val cleaner = createCleaner(memory) {
c_lib_free(it.foo)
c_lib_free(it.bar)
}
}
This can also work if the pointer is a var
and might be freed and replaced within the lifecycle of the wrapper and just need to ensure the last var
set is freed on GC.Landry Norris
03/14/2023, 5:52 PMJeff Lockhart
03/14/2023, 5:55 PMit
reference within the cleaner.
I like that it does make it explicit any memory that needs freeing should be kept in that one place.Landry Norris
03/14/2023, 5:57 PMJeff Lockhart
03/14/2023, 6:01 PMBig Chungus
03/14/2023, 6:02 PMJeff Lockhart
03/14/2023, 6:04 PMBig Chungus
03/14/2023, 6:06 PMval foo by memory::foo
Landry Norris
03/14/2023, 6:10 PMJeff Lockhart
03/14/2023, 6:11 PMLandry Norris
03/14/2023, 6:12 PM