Tracking object lifetimes in Kotlin Native

In my multiplatform project I need to work with bignums. In the JVM and JS targets, this is easy and I’ve created a wrapper around the built-in bignum functionality on those platforms.

On Linux, I leverage the gmp library to achieve the same goal. In gmp, when you’re done with a value, you need to call mpz_clear to release the memory used by the bignum.

I’ve noticed that the finalize function does not work in Kotlin Native, so what is the solution here? Due to the nature of the project, explicit scoping for these values is not an option. I somehow need to know when the Kotlin object that wraps the gmp value is garbage collected.

Is there a solution to this problem?

1 Like

I managed to figure it out. I’m adding the answer here in case anyone else is searching for the same solution.

Kotlin provides an experimental API: kotlin.native.internal.Cleaner. It does exactly what I needed it to do.

Make sure you read the explanation in the reference documentation. Specifically, it’s very important that the cleanup handler does not hold a reference to the outer object. It’s very easy to accidentally do that, as I experienced when adding a call to println in the handler to see if it was called.

1 Like