Kotlin 多平台中的 CPointer

Dmi*_*tri 2 c kotlin swift kotlin-native kotlin-multiplatform

我找不到任何有关如何在 Kotlin Multiplatform 中获取 CPointer 的示例,并且现有文档也没有多大帮助。在我的 iOS 源代码集中,我需要构建与以下 Swift 代码等效的 Kotlin(仅包括代码的相关部分):

  ...(hex: String) {

if hex.hasPrefix("#") {
    let start = hex.index(hex.startIndex, offsetBy: 1)
         let scanner = Scanner(string: hexColor)
         var hexNumber: UInt64 = 0



          if scanner.scanHexInt64(&hexNumber) {

            r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
           ....
Run Code Online (Sandbox Code Playgroud)

我遇到问题的具体部分是

扫描仪.scanHexInt64(&hexNumber)

这是 Kotlin 代码和问题

//input to function - hex: String
    val scanner = NSScanner(hex)
    if (hex.startsWith("#")) {
        scanner.scanLocation = 1u
    }
    var hexNumber : UInt32 = 0u
    /*Type mismatch.
    Required:
    CPointer<UIntVar /* = UIntVarOf<UInt> */>?
    Found:
    UInt32 /* = UInt */
     */
    //HOW TO GET CPOINTER TO hexNumber?
    scanner.scanHexInt(hexNumber)
Run Code Online (Sandbox Code Playgroud)

根据文档:(链接)

指针和数组映射到CPointer<T>?.

但如何呢?

Dmi*_*tri 6

找到了我的问题的答案。必须使用

内存范围

memScoped {
        var pointed : UIntVar = alloc<UIntVar>()
        scanner.scanHexInt(pointed.ptr)
        val alpha: CGFloat = 1.0
        val pointedValue = pointed.value
        val r: CGFloat = (((pointedValue and 0xFF0000) shr 16)/255.0)
        ....
}
Run Code Online (Sandbox Code Playgroud)

互联网上关于此的唯一来源(关于应用它来获取指针)在这里 -链接

内存范围

inline fun <R> memScoped(block: MemScope.() -> R): R
Runs given block providing allocation of memory which will be automatically disposed at the end of this scope
Run Code Online (Sandbox Code Playgroud)

其中,使用扩展函数alloc()获取CVariable

fun <reified T : CVariable> NativePlacement.alloc(): T
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过另一个扩展函数访问指针

val <T : CPointed> T.ptr: CPointer<T>
Run Code Online (Sandbox Code Playgroud)

回想起来,一切都非常清楚,并且很清楚,最初以错误的方式解决了问题,希望通过类似CPointer<UInt> = ... 官方文档https://kotlinlang.org/docs/reference/native/c_interop.html来获取指针