Hi, Iam working on a Kotlin Multiplatform Project ...
# kotlin-native
s
Hi, Iam working on a Kotlin Multiplatform Project that also contains native targets for linux and windows. At the native part I have significant issues with memory leaks when creating a kotlin object within C. Can someone help me with this? In kotlin commonMain, for example, I have the following classes:
Copy code
@Serializable
public data class DictionaryEntry(
    @SerialName("Label")
    val label: String,
)


public class MyWorker(val data: Array<DictionaryEntry>) {
	val mappedData = data.map{it.label}
}
I also had a function to create the Array of DictionaryEntrys:
Copy code
public fun createDictionaryEntry(label: String): COpaquePointer {
    val entry = DictionaryEntry(label)
    val ref = StableRef.create(entry)
    return ref.asCPointer()
}
fun makeList(ptr: CArrayPointer<COpaquePointerVar>, size:Int): COpaquePointer {
    val intermediate = ArrayList<DictionaryEntry>(size)
    for (index in 0 until size){
        val ref = ptr[index]!!.asStableRef<DictionaryEntry>()
        intermediate.add(ref.get())
        ref.dispose()
    }
    println("size of list is: ${intermediate.size}")

    val ref = StableRef.create(intermediate)
    return ref.asCPointer()
}
So far so good. I can create the array with the entries and release it again with the DisposeStablePointer function without having memory leaks. However, if I create an object of the MyWorker class, the whole thing leaks. I have tried the following approaches here: C++ Code:
Copy code
void* worker1 = MyKotlinLib::instance()->kotlin.root.createMyWorker(dictionaryEntries.pinned);
MyKotlinLib::instance()->DisposeStablePointer(worker)
Kotlin Code:
Copy code
public fun createMyWorker(ptr: COpaquePointer) : COpaquePointer{
    val dict = ptr.asStableRef<ArrayList<DictionaryEntry>>()
    val worker = MyWorker(dict.get().toList())
    val ref = StableRef.create(worker)
    dict.dispose()
    return ref.asCPointer()
}
and this approach: C++ Code:
void* worker = MyKotlinLib::instance()-><http://kotlin.root.de|kotlin.root.de>.MyWorker.MyWorker(dictionaryEntries.pinned)
Any ideas how to avoid the memory leaks here?