我正在尝试使用以下代码获取UnsafeMutableBufferPointer,它有时在Playground中运行,但也失败了
let array : [Character] = ....
func getUnsafeMP(array: [Character]) -> UnsafeMutableBufferPointer<Character> {
let count = array.count
let memory = UnsafeMutablePointer<Character>(allocatingCapacity: count)
for (index , value) in array.enumerated() {
memory[index] = value //it fails here EXC_BAD_ACCESS
}
let buffer = UnsafeMutableBufferPointer(start: memory, count: count)
return buffer
}
答案 0 :(得分:5)
UnsafeMutablePointer
解决的内存可能属于其中之一
三个州:
/// - Memory is not allocated (for example, pointer is null, or memory has
/// been deallocated previously).
///
/// - Memory is allocated, but value has not been initialized.
///
/// - Memory is allocated and value is initialised.
电话
let memory = UnsafeMutablePointer<Character>(allocatingCapacity: count)
分配内存,但不初始化:
/// Allocate and point at uninitialized aligned memory for `count`
/// instances of `Pointee`.
///
/// - Postcondition: The pointee is allocated, but not initialized.
public init(allocatingCapacity count: Int)
另一方面,下标方法要求初始化指针:
/// Access the pointee at `self + i`.
///
/// - Precondition: the pointee at `self + i` is initialized.
public subscript(i: Int) -> Pointee { get nonmutating set }
因此,您的代码在_swift_release_
内崩溃。
要从(字符)数组初始化分配的内存, 你可以用
memory.initializeFrom(array)
当然,你必须最终取消初始化和释放内存。
另一种方法是
var cArray: [Character] = ["A", "B", "C"]
cArray.withUnsafeMutableBufferPointer { bufPtr in
// ...
}
这里没有分配新的内存,但是调用了闭包 指向数组连续存储的指针。这个缓冲区指针 仅在封闭内有效。
答案 1 :(得分:2)
您可能正在寻找Array的withUnsafeBufferPointer
方法。这使您可以直接访问阵列的连续内存存储。你可能想要从这样的事情开始:
let arr = Array("hello there".characters)
arr.withUnsafeBufferPointer { p -> Void in
var i = 0
repeat {
print("character:", p[i])
i += 1
} while i < p.count
}