简体   繁体   中英

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())
}

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())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM