jl303 jl303 - 1 year ago 121
Objective-C Question

Working with ObjC Functions with UnsafeMutableRawPointer or UnsafeMutablePointer Parameter from Swift?

I'm new to swift, and Im trying to work with ObjC function that has a parameter type UnsafeMutablePointer. I read many posts about working with UnsafeMutablePointer or UnsafeMutableRawPointer, but I couldn't still get it to work. The function is:

func AXUIElementCopyAttributeNames(_ element: AXUIElement, _ names: UnsafeMutablePointer) -> AXError

I even found the question for exact function, but the answer does not seem to work any more in swift 3. Here are some of the things that I tried that didn't work.

var ptr : Unmanaged<CFArray>? = nil
AXUIElementCopyAttributeNames(element, &ptr)

var names:CFArray? = nil
AXUIElementCopyAttributeNames(element, UnsafeMutablePointer(names))

var names:CFArray? = nil
AXUIElementCopyAttributeNames(element, UnsafeMutablePointer<CFArray>(Unmanaged.passUnretained(names).toOpaque()))

Also, is there a good tutorial that would give me solid grasp on working with ObjC functions in Swift 3? It seems there are still many apis missing in swift.

Thank you very much!

Answer Source

AXUIElementCopyAttributeNames does not take a pointer to an unmanaged CFArray anymore:

let element: AXUIElement = ...

var cfArray: CFArray?
let error = AXUIElementCopyAttributeNames(element, &cfArray)
if error == .success, let names = cfArray as? [String] {
    // names is [String] array ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download