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

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!