gpt4 book ai didi

swift - 如何从字符数组中获取 UnsafeMutableBufferPointer

转载 作者:搜寻专家 更新时间:2023-11-01 05:53:28 24 4
gpt4 key购买 nike

我正在尝试使用以下代码获取 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
}

最佳答案

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

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

关于swift - 如何从字符数组中获取 UnsafeMutableBufferPointer<Character>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38293446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com