# kotlin-native

Sven Wiegand

02/27/2024, 2:07 PM
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
public data class DictionaryEntry(
    val label: String,

public class MyWorker(val data: Array<DictionaryEntry>) {
	val mappedData ={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>()
    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);
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)
    return ref.asCPointer()
and this approach: C++ Code:
void* worker = MyKotlinLib::instance()-><|>.MyWorker.MyWorker(dictionaryEntries.pinned)
Any ideas how to avoid the memory leaks here?