我有一个带有此功能的遗留代码库:
-(void)foo: (int *)buffer {
myArray[0] = buffer[0];
myArray[1] = buffer[1];
myArray[2] = buffer[2];
myArray[3] = buffer[3];
}
在Swift中,此方法编写如下:
func foo(buffer: UnsafeMutablePointer<Int32>) {
}
int
指针现在被视为UnsafeMutablePointer<UInt32>
。我无法访问Swift中buffer
的下标;即我不能这样打buffer[0]
:
func foo(buffer: UnsafeMutablePointer<Int32>) {
myArray[0] = buffer[0] // won't compile, buffer treated as Int32
}
出于绝望,即使知道UnsafeMutablePointer<Int32>
最终在Swift中被解析为Int32
类型,我也尝试了以下内容:
guard let buffer = buffer.memory as? [Int] else { fatalError() }
guard let buffer = buffer as? [Int] else { fatalError() }
guard let buffer = buffer.memory as? [Int32] else { fatalError() }
guard let buffer = buffer as? [Int32] else { fatalError() }
有人能指出我正确的方向,了解我如何能够像Objective-C代码那样访问下标成员吗?
答案 0 :(得分:3)
UnsafePointer
用于模拟内存中的单个位置。要处理缓冲区,请使用UnsafeBufferPointer
。
UnsafeBufferPointer
可以像Array
一样下标,并且已经绑定了检查(因为它要求你给它count
)。
您甚至不必像在Objective C代码中那样进行手动转换,您可以非常轻松地直接从Array
初始化UnsafeBufferPointer
:
func foo(buffer: UnsafeMutablePointer<Int32>) {
myArray = Array(UnsafeBufferPointer(start: pointer, count: 4))
}
此解决方案甚至是通用的:UnsafeBufferPointer
可以从您提供的UnsafePointer
推断其类型,并将该信息传递给Array
,以使其自动创建{{1} }}
注意:请记得取消分配您的UnsafePointer!
答案 1 :(得分:2)
你正在思考它:
class MyClass {
var myArray = [Int32](count: 4, repeatedValue: 0)
func foo(buffer: UnsafeMutablePointer<Int32>) {
for i in 0..<4 {
myArray[i] = buffer[i]
}
}
}
您可以将myArray
更改为[Int32]
,使其与buffer
匹配。或者您可以将buffer
投射到Int
:
myArray[i] = Int(buffer[i])
答案 2 :(得分:1)
也许您改为使用UnsafeBufferPointer
?