Native: add detachObjCObject internal function for Obj-C objects

For a Kotlin wrapper of an Objective-C object, this functions zeroes
and releases the strong reference from the Kotlin wrapper to the
Objective-C object.
Usually, such a release happens only when the Kotlin wrapper is GCed.
So using this function can help that happen sooner.

^KT-59134
This commit is contained in:
Svyatoslav Scherbina
2023-06-01 15:42:31 +02:00
committed by Space Team
parent 6521729466
commit 1bf3d55bdf
6 changed files with 154 additions and 1 deletions
@@ -0,0 +1,28 @@
/*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlinx.cinterop.internal
import kotlin.native.internal.GCUnsafeCall
import kotlin.native.internal.InternalForKotlinNative
import kotlinx.cinterop.BetaInteropApi
import kotlinx.cinterop.ObjCObject
/**
* Detaches the Objective-C object from this Kotlin wrapper. More specifically, releases the Obj-C reference and zeroes
* the field where it is stored.
*
* This doesn't affect other possible Kotlin wrappers of this Objective-C object. Typically, when an Objective-C
* object gets into Kotlin, a new Kotlin wrapper is created, even if there is another wrapper already exists. To get
* the Objective-C object actually deallocated, each Kotlin wrapper should first be either GCed or detached with this
* function.
*
* If you use this object (Kotlin wrapper) after calling this function, the program behavior is undefined.
* In particular, it can crash.
*/
@InternalForKotlinNative
@GCUnsafeCall("Kotlin_objc_detachObjCObject")
@OptIn(BetaInteropApi::class)
public external fun detachObjCObject(obj: ObjCObject)