0

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?

digory doo
  • 1,978
  • 2
  • 23
  • 37
  • 1
    I'm not familiar with kotlin-native, so I can't tell you what to do *instead*. But the [documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/c-values-of.html) for `cValuesOf` indicates that the returned sequence is immutable. So you shouldn't pass it to a C function that expects to mutate it. – Silvio Mayolo Dec 16 '22 at 15:08

1 Answers1

1

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
        }
    }
}
Jeff Lockhart
  • 5,379
  • 4
  • 36
  • 51