Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

macos

swift

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>.

like image 377
Laxsnor Avatar asked Oct 18 '22 09:10

Laxsnor


1 Answers

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.

like image 95
Laxsnor Avatar answered Oct 21 '22 03:10

Laxsnor