https://kotlinlang.org logo
#kotlin-native
Title
# kotlin-native
j

Jeff Lockhart

07/25/2022, 5:19 AM
What would be the behavior of `pin()`ing a
ByteArray
and not `unpin()`ing it? Would this only prevent GC from relocating the memory, or would it cause a memory leak? My issue is with returning a native pointer to an internal
ByteArray
buffer as a stable reference, where the caller uses the pointer, but can't call
unpin()
after doing so.
l

Landry Norris

07/25/2022, 7:23 PM
From what I’ve seen, I believe that pinning a variable prevents the GC from collecting it until it’s unpinned. If you look at the runtime source code, you’ll see that pinning writes to a ‘hidden’ member of every K/N class that the runtime can read.
j

Jeff Lockhart

07/25/2022, 8:08 PM
Interesting, so it does add a strong reference, which would hold it in memory until unpinned, even if all other references are released. We ended up coming up with a solution to this by unpinning the pinned buffer on either the next method call, before pinning another reference, or in the
close()
function, which would guarantee the buffer gets released when closed.
l

Landry Norris

07/25/2022, 8:10 PM
It looks like it marks the object as stable (Same as StableRef.create()) under the hood, which tells the GC that the object can neither be freed nor moved, as the pointer is being used. This is a feature of the Kotlin/Native runtime.
23 Views