简体   繁体   English

kotlin native 给 c 指针加上偏移量

[英]kotlin native adding a value to c pointer with offset

In Kotlin Native i have a CPointer to a struct.在 Kotlin Native 中,我有一个指向结构的 CPointer。 I need to add the address of a CFuncton to that pointer with an offset.我需要将 CFuncton 的地址添加到具有偏移量的指针。 Is this possible with kotlin native. kotlin 本机是否可能? 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.不幸的是,NativePtr 上的文档非常少,而且代码文档不存在,这使得找到解决方案变得非常困难。

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)我尝试了这段代码,但得到了编译错误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 .您只需要使用interpretCPointer将本机指针转换为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())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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