Laxsnor Laxsnor - 1 month ago 8x
C Question

Cannot convert value of type 'UnsafePointer<Double>' to expected argument type 'UnsafePointer<_>'

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

(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
. I tried converting to
, but that got the same error. Swift does recognize that
is a


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.