I'm working with an external C library in Swift for OS X. I get a value cda, which is defined in C as a double*
(it is a pointer to a double array).
When importing into Swift, it recognizes the type as UnsafeMutablePointer. I'm trying to convert this pointer and the count into a double array. Here's the code that I'm using (assume arrlen is the correct count of the array):
let doublearrptr = UnsafePointer<Double>(cda)
let xptarr = UnsafeBufferPointer<Double>(start: doublearrptr, count:arrlen)
However, when compiling this code fragment, I get the error:
Cannot convert value of type 'UnsafePointer<Double>' to expected argument type 'UnsafePointer<_>'
I'm relatively new to Swift, but I'm fairly certain that I can't convert to UnsafePointer<_>
. I tried converting to UnsafePointer<Void>
, but that got the same error. Swift does recognize that cda
is a UnsafeMutablePointer<Double>
.
So, I was able to solve it, albeit in a roundabout way.
I created a new function convert and used it:
func convertArr<T>(count: Int, data: UnsafePointer<T>) -> [T] {
let buffer = UnsafeBufferPointer(start: data, count: count)
return Array(buffer)
}
...
let doublearrptr = UnsafePointer<Double>(cda)
let arr = convertArr(Int(shobjarrlen), data: doublearrptr)
For some reason this works but not the original syntax...
I'm still open to getting answers from why my original syntax didn't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With