objective-c - 在 Swift 中访问 Objective-C 指针

标签 objective-c swift pointers

我有这个 Objective-C 代码片段,我想用 Swift 表达它

CFArrayRef windowList;
AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute, (CFTypeRef *)&windowList);

if ((!windowList) || CFArrayGetCount(windowList)<1)
        continue;

AXUIElementRef windowRef = (AXUIElementRef) CFArrayGetValueAtIndex( windowList, 0);
CFTypeRef role;
AXUIElementCopyAttributeValue(windowRef, kAXRoleAttribute, (CFTypeRef *)&role);         

我不确定的第一件事是:谁分配了 windowListPointer 后面的内存。 我尝试过这个片段:

var windowListPointer : UnsafeMutablePointer<Optional<AnyObject>>
AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, windowListPointer );

但这甚至无法编译:它提示,windowListPointer 未初始化。 我可以创建什么对象,让 WindowListPointer 指向?

最佳答案

如果您通过 UnsafeMutablePointer<Optional<AnyObject>>作为最后一个 AXUIElementCopyAttributeValue() 的参数那么你必须 通过分配(并最终释放)内存来初始化它:

var resultPtr: UnsafeMutablePointer<Optional<AnyObject>> = UnsafeMutablePointer.allocate(capacity: 1)
resultPtr.initialize(to: nil)

let result = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, resultPtr)
// ...

resultPtr.deinitialize()
resultPtr.deallocate(capacity: 1)

这样更容易 传递 Optional<AnyObject> 的地址多变的 与 & 。然后有条件地 将接收到的对象转换为预期类型,在本例中为 AXUIElement 数组:

var value: AnyObject?
let result = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, &value)
if result == .success, let windowList = value as? [AXUIElement] {
    // use `windowList`
}

同样:

if let window = windowList.first {
    var value: AnyObject?
    let result = AXUIElementCopyAttributeValue(window, kAXRoleAttribute as CFString, &value)
    if result == .success, let role = value as? String {
        // use `role` ...
    }
}

我们可以定义一个通用的实用函数来封装 所有 Actor :

func axUICopyAttributeValue<T>(of element: AXUIElement, attribute: String, as type: T.Type) -> T? {
    var value: AnyObject?
    let result = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
    if result == .success, let typedValue = value as? T {
        return typedValue
    }
    return nil
}

使用示例:

if let windowList = axUICopyAttributeValue(of: appRef, attribute: kAXWindowsAttribute, as:[AXUIElement].self) {

    for window in windowList {
        if let role = axUICopyAttributeValue(of: window, attribute: kAXRoleAttribute, as: String.self) {

            // ...
        }
    }
}

关于objective-c - 在 Swift 中访问 Objective-C 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47487193/

相关文章:

ios - ios 中的算术和条件表达式求值器(包含字符串和值)

ios - 如何在 Mkmapview 中拖放注释图钉

objective-c - @synthesize 用于类变量

iphone - Xcode 4 核心数据 : How to use fetched property created in Data Model editor

ios - 如何将工作日分配给按钮?

pointers - 戈朗 : How to append pointer to slice to slice?

swift - 使用 UITextChecker 对 Swift 5 中的希伯来语文本进行拼写检查

ios - 如何在 SwiftUI 环境中实现子上下文(CoreData)?

c++ - C++中的抽象类指针

c++ - 类型转换指针