如何从Character数组中获取UnsafeMutableBufferPointer <Character>

Bob*_*j-C 1 swift swift3 unsafemutablepointer

我试图使用以下代码获取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
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 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.
Run Code Online (Sandbox Code Playgroud)

电话

let memory = UnsafeMutablePointer<Character>(allocatingCapacity: count)
Run Code Online (Sandbox Code Playgroud)

分配内存,但不初始化它:

/// 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)
Run Code Online (Sandbox Code Playgroud)

另一方面,下标方法要求初始化指针:

/// Access the pointee at `self + i`.
///
/// - Precondition: the pointee at `self + i` is initialized.
public subscript(i: Int) -> Pointee { get nonmutating set }
Run Code Online (Sandbox Code Playgroud)

结果,你的代码崩溃了_swift_release_.

要从(字符)数组初始化分配的内存,您可以使用

memory.initializeFrom(array)
Run Code Online (Sandbox Code Playgroud)

当然,您必须最终取消初始化并释放内存.


一种不同的方法是

var cArray: [Character] = ["A", "B", "C"]
cArray.withUnsafeMutableBufferPointer { bufPtr  in
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这里没有分配新内存,但是使用指向数组连续存储的指针调用闭包.此缓冲区指针仅在闭包内有效.