在swift中Memset到UnsafeMutablePointer <UInt8>

CrA*_*HeR 4 pointers allocation swift

我对带有类型的变量提出了挑战UnsafeMutablePointer<UInt8>.

我有这个工作代码来分配并设置为零UInt8在Swift中的所有数组.
var bits = UnsafeMutablePointer<UInt8>(calloc(width * height, 8))

问题是我想在不使用calloc方法的情况下这样做.我有这个代码来分配数组
var bits = UnsafeMutablePointer<UInt8>.alloc(width * height)

但我找不到一个方法来设置所有内存为零.

我知道我可以做到这一点,但我认为这不是最好的方法.

for index in 0..< (width * height) {
    bits[index] = 0
}
Run Code Online (Sandbox Code Playgroud)

Air*_*ity 11

正如@matt建议的那样,您可以使用initializeFrom初始化内存.我会使用Repeat集合类型,因为它避免任何临时分配:

var bits = UnsafeMutablePointer<UInt8>.alloc(width * height)
bits.initializeFrom(Repeat(count: width * height, repeatedValue: 0))
Run Code Online (Sandbox Code Playgroud)

(注意,没有必要给出值的类型Repeat,可以从类型中推断出来bits)

如果你发现你做了很多,可能值得创建一个类似calloc的扩展UnsafeMutablePointer:

extension UnsafeMutablePointer {
    // version that takes any kind of type for initial value
    static func calloc(num: Int, initialValue: T) -> UnsafeMutablePointer<T> {
        let ptr = UnsafeMutablePointer<T>.alloc(num)
        ptr.initializeFrom(Repeat(count: num, repeatedValue: initialValue))
        return ptr
    }

    // convenience version for integer-literal-creatable types 
    // that initializes to zero of that type
    static func calloc<I: IntegerLiteralConvertible>
      (num: Int) -> UnsafeMutablePointer<I> {
        return UnsafeMutablePointer<I>.calloc(num, initialValue: 0)
    }
}

// creates 100 UInt8s initialized to 0
var bits = UnsafeMutablePointer<UInt8>.calloc(100)
Run Code Online (Sandbox Code Playgroud)


mat*_*att 2

你可以说:

bits.initializeFrom(Array<UInt8>(count: width * height, repeatedValue: 0))
Run Code Online (Sandbox Code Playgroud)

我猜想以这种方式复制内存有一些潜在的效率。但当然,我们临时制作数组会导致效率低下。[注:AirspeedVelocity 的答案显示了一种避免这种情况的方法。]

就我个人而言,我最喜欢你原来的循环,特别是如果你把它写得更紧凑,就像这样:

(0 ..< (width*height)).map {bits[$0] = 0}
Run Code Online (Sandbox Code Playgroud)