I'm struggling with Kotlin and toll-free bridging ...
# kotlin-native
s
I'm struggling with Kotlin and toll-free bridging with CF APIs. Code Sample and output are in the thread. 1. Is there a better way I should be using toll-free bridging in Kotlin? It seems almost automatic in Swift. 2.
CGWindowListCopyWindowInfo()
returns an Array of Maps. When I bridge the result with
CFBridgingRelease()
, the result is an NSArray of Kotlin maps. Why can't it be a kotlin Array of Kotlin maps? Is there a way for me to manually bridge an NSArray to a Kotlin Array?
Here is a piece of sample code:
Copy code
import platform.CoreGraphics.*
import platform.Foundation.*
import platform.CoreFoundation.*

fun main(args: Array<String>) {
    val windowInfo: NSArray = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID)!!.bridgingRelease()
    println("Size: " + windowInfo.count)
    
    val map = windowInfo.objectAtIndex(0) as Map<String, Any>
    println("Type: ${map::class.simpleName}")

    for ((key, value) in map) {
        println("Key: $key, Value: ${value::class.qualifiedName} $value")
    }
}

@Suppress("UNCHECKED_CAST")
fun CFArrayRef.bridgingRelease(): NSArray {
    val releasedItem = CFBridgingRelease(this as CFTypeRef)!!
    return releasedItem as NSArray
}
Here is the output:
Copy code
Size: 112
Type: NSDictionaryAsKMap
Key: kotlin.String kCGWindowLayer, Value: kotlin.Long 102
Key: kotlin.String kCGWindowAlpha, Value: kotlin.Double 1.0
Key: kotlin.String kCGWindowMemoryUsage, Value: kotlin.Long 5384
Key: kotlin.String kCGWindowSharingState, Value: kotlin.Long 1
Key: kotlin.String kCGWindowOwnerPID, Value: kotlin.Long 33792
Key: kotlin.String kCGWindowNumber, Value: kotlin.Long 4074
Key: kotlin.String kCGWindowOwnerName, Value: kotlin.String AppCode
Key: kotlin.String kCGWindowStoreType, Value: kotlin.Long 2
Key: kotlin.String kCGWindowBounds, Value: konan.internal.NSDictionaryAsKMap {X=100.0, Height=1.0, Y=100.0, Width=1.0}
Key: kotlin.String kCGWindowName, Value: kotlin.String Focus Proxy
s
Why can’t it be a kotlin Array of Kotlin maps? Is there a way for me to manually bridge an NSArray to a Kotlin Array?
NSArray
is mapped to Kotlin
List
. You can cast
releasedItem
to Kotlin list of Kotlin maps:
Copy code
return releasedItem as List<Map<String, Any>>
s
I didn't think I'd get a response on this. Wow, thanks! That's even more convenient