0

How can I use UnsafeMutablePointer<T?> as UnsafeMutablePointer<UnsafeRawPointer?>!

e.g. Trying to allocate n blocks of memory for type T, to get values from a CFSet cfsetref:

var array = UnsafeMutableRawPointer<T?>.allocate(capacity: n)
CFSetGetValues(cfsetref, array) // error

Which gives the error

Cannot convert value of type 'UnsafeMutablePointer<T?>' to expected argument type 'UnsafeMutablePointer<UnsafeRawPointer?>!'

I tried declaring array as UnsafeMutablePointer<UnsafeRawPointer?> then doing

for i in 0..<n {
  var d = array[i]
  d?.bindMemory(to: T.self, capacity: 1)
}

But I still get EXC_BAD_INSTRUCTION errors when attempting to access array[i] (after binding the memory again to T)

1 Answer 1

3

Many things depends on how you get your cfsetref and what actually is T.

But anyway, CFSetGetValues expects UnsafeMutablePointer<UnsafeRawPointer?>! as shown in the error message.

let n = CFSetGetCount(cfsetref)
let array = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: n)
array.initialize(to: nil, count: n)
CFSetGetValues(cfsetref, array)

To safely access the contents of array, you need to know how T is managed by Swift ARC. For example, assuming T is NSNumber, you need to tell Swift ARC to manage the result with writing something like this:

let managedArray = UnsafeMutableBufferPointer(start: array, count: n).map{Unmanaged<NSNumber>.fromOpaque($0!).takeRetainedValue()}
print(managedArray)

But as well as other CF-collection types, the better way to handle CFSet is bridging it to Swift Set:

if let swiftSet = cfsetref as? Set<NSNumber> {
    let swiftArray = Array(swiftSet)
    print(swiftArray)
}

How do you get your cfsetref and what actually is T? With such information, I would try to tell you what sort of code you need to write in your actual case.

Sign up to request clarification or add additional context in comments.

1 Comment

Bridging to Set feels right. My CFSet is coming from IOHIDManagerCopyDevices, where T is a IOHIDDevice. I was getting nowhere trying to manage my own pointers/memory, but bridging to Set seems to work out of the box (and is so much simpler). Thanks so much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.