kotlinkotlin-nativecinterop

Pass value from Kotlin/native to C


How do I pass a value from Kotlin to C as an int* and receive the written value? The C function looks like this:

int readValue(long param, int *value);

The return value is just 1 or 0 indicating success or failure. The actual value that was read is passed back through the value pointer. I tried wrapping a Kotlin Int with cValuesOf:

import interop.readValue

fun doIt(): Boolean {
    val arg = cValuesOf(0) // This should give me a CValue<Int>, right?
    val result = readValue(42L, arg) // Here I call the C function
    
    if (result == 0) {
        return false
    } else {
        println("Read value: ${arg.value}") // doesn't work, there is no arg.value
        return true
    }
}

But I can't get the result out from it after the call. How do I do this properly?


Solution

  • Because Kotlin doesn't allocate variables on the stack as C does, you need to allocate an int* as a Kotlin IntVarOf<Int> on the heap. memScoped() provides a memory scope where allocated memory will be automatically deallocated at the end of the lambda block.

    fun doIt(): Boolean {
        return memScoped {
            val arg = alloc<IntVar>()
            val result = readValue(42L, arg.ptr)
    
            if (result == 0) {
                false
            } else {
                println("Read value: ${arg.value}")
                true
            }
        }
    }