Search code examples
kotlin-multiplatformkotlin-native

kotlin native adding a value to c pointer with offset


In Kotlin Native i have a CPointer to a struct. I need to add the address of a CFuncton to that pointer with an offset. Is this possible with kotlin native. The offset is only known at run time.

Unfortunately the documentation on NativePtr is extremly minimal and code doc is non existing makes finding a solution extreme hard.

I tried this code but got the compile error Native interop types constructors must not be called directly because of this line: CPointerVarOf<COpaquePointer>(offsetPtr)

fun main() {
    val genericStructPointer: CPointer<out CPointed> = malloc(100)!!
    println("genericStructPointer: ${genericStructPointer.rawValue}") // 0x955d60

    val offsetPtr = genericStructPointer.rawValue.plus(16)
    println("offsetPtr: $offsetPtr") // 0x955d70

    val squareFunc = staticCFunction<Int, Int>{ x -> x * x}
    println("func adr: ${squareFunc.rawValue}") //0x4185f0

    val size = sizeOf<CPointerVarOf<COpaquePointer>>()
    println("size: $size") // 8

    val destPointer = CPointerVarOf<COpaquePointer>(offsetPtr) // <= compile exception: Native interop types constructors must not be called directly
    memcpy(destPointer.value, squareFunc, size.toULong())
}

Solution

  • You just need to use interpretCPointer which cast native pointer to CPointer. Finally code will look:

    fun main() {
        val genericStructPointer: CPointer<out CPointed> = malloc(100)!!
        //...
        val offsetPtr = genericStructPointer.rawValue.plus(16)
        val destPointer = interpretCPointer<CPointed>(offsetPtr)
        memcpy(destPointer, squareFunc, size.toULong())
    }