我正在尝试获取特定窗口的pid_t(使用CGWindowListCopyWindowInfo)。在swift中使用类型转换进行战斗后我终于可以获得windowOwnerPID
var windowOwnerPIDRef = CFDictionaryGetValue(windowInfoRef, unsafeAddressOf(kCGWindowOwnerPID))
var windowOwnerPID = unsafeBitCast(windowOwnerPIDRef, AnyObject.self)
现在我需要将变量windowOwnerPID从AnyObject转换为pid_t以进入函数
var appRef: AXUIElement = AXUIElementCreateApplication(testPid).takeRetainedValue()
但不知道该怎么做。任何人都有这方面的经验吗?
答案 0 :(得分:2)
根据documentation,kCGWindowOwnerPID
键的值是CFNumberRef
类型(编码为kCFNumberIntType
),其中包含拥有该应用程序的应用程序的进程ID窗口。
使用CoreFoundation和Foundation类型之间的免费桥接 在Foundation和Swift类型之间,以下内容应该有效:
let wlist = CGWindowListCopyWindowInfo(
CGWindowListOption(kCGWindowListOptionOnScreenOnly), 0).takeRetainedValue()
for wdict in wlist as [ [ String : AnyObject] ] {
if let pid = wdict[kCGWindowOwnerPID] as? Int {
println(pid)
// pid is an Int here. If necessary, convert to pid_t with
let pidd = pid_t(pid)
}
}
(因此甚至不需要调用unsafeAddressOf()
和unsafeBitCast()
。)
使用Swift 1.2(Xcode 6.3 beta)进行显式转换
需要CFStringRef
到String
(感谢Rob Napier
反馈):
let wlist = CGWindowListCopyWindowInfo(
CGWindowListOption(kCGWindowListOptionOnScreenOnly), 0).takeRetainedValue()
for wdict in wlist as! [ [ String : AnyObject] ] {
if let pid = wdict[String(kCGWindowOwnerPID)] as? Int {
println(pid)
}
}