无法转换类型为'UnsafePointer< Double>'的值到预期的参数类型'UnsafePointer< _>' [英] Cannot convert value of type 'UnsafePointer<Double>' to expected argument type 'UnsafePointer<_>'
问题描述
我正在Swift中为OS X使用外部C库.我得到一个值cda,在C中它定义为double*
(它是一个双精度数组的指针).
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).
当导入Swift时,它会将类型识别为UnsafeMutablePointer.我正在尝试将此指针和计数转换为双精度数组.这是我正在使用的代码(假设arrlen是数组的正确计数):
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<_>'
我对Swift还是比较陌生,但是我可以肯定我无法转换为UnsafePointer<_>
.我尝试转换为UnsafePointer<Void>
,但是得到了相同的错误. Swift确实认识到cda
是UnsafeMutablePointer<Double>
.
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.
我创建了一个新的函数convert并使用了它:
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.
这篇关于无法转换类型为'UnsafePointer< Double>'的值到预期的参数类型'UnsafePointer< _>'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!