【问题标题】:How to migrate array.withUnsafeMutableBufferPointer from swift 2 to swift 3?如何将 array.withUnsafeMutableBufferPointer 从 swift 2 迁移到 swift 3?
【发布时间】:2017-04-14 15:35:48
【问题描述】:

我想使用来自this link 的代码 在 swif 2 中

public protocol SGLImageType {
    typealias Element
    var width:Int {get}
    var height:Int {get}
    var channels:Int {get}
    var rowsize:Int {get}
    
    func withUnsafeMutableBufferPointer(
        @noescape body: (UnsafeMutableBufferPointer<Element>) throws -> Void
    ) rethrows
}

上面协议实现的类:

final public class SGLImageRGBA8 : SGLImageType { ... public func withUnsafeMutableBufferPointer(@noescape body: (UnsafeMutableBufferPointer<UInt8>) throws -> Void) rethrows {
    try array.withUnsafeMutableBufferPointer(){
        // This is unsafe reinterpret cast. Be careful here.
        let st = UnsafeMutablePointer<UInt8>($0.baseAddress)
        try body(UnsafeMutableBufferPointer<UInt8>(start: st, count: $0.count*channels))
    }
}

在 swift 3 中,let st = UnsafeMutablePointer&lt;UInt8&gt;($0.baseAddress) 行抛出此错误:

'init' 不可用:使用 'withMemoryRebound(to:capacity:_)' 暂时将内存视为另一种布局兼容的类型

如何解决这个错误?

【问题讨论】:

标签: swift swift3 swift2


【解决方案1】:

您可以将UnsafeMutableBufferPointer&lt;UInt8&gt; 转换为UnsafeMutableRawBufferPointer,将其绑定到UInt8 并从中创建一个UnsafeMutableBufferPointer&lt;UInt8&gt;(在此处对所有属性使用虚拟值):

final public class SGLImageRGBA8 : SGLImageType {
    public var width: Int = 640
    public var height: Int = 480
    public var channels: Int = 4
    public var rowsize: Int = 80
    public var array:[(r:UInt8,g:UInt8,b:UInt8,a:UInt8)] =
        [(r:UInt8(1), g:UInt8(2), b:UInt8(3), a:UInt8(4))]

    public func withUnsafeMutableBufferPointer(body: @escaping (UnsafeMutableBufferPointer<UInt8>) throws -> Void) rethrows {
        try array.withUnsafeMutableBufferPointer(){ bp in
            let rbp = UnsafeMutableRawBufferPointer(bp)
            let p = rbp.baseAddress!.bindMemory(to: UInt8.self, capacity: rbp.count)
            try body(UnsafeMutableBufferPointer(start: p, count: rbp.count))
        }
    }
}

SGLImageRGBA8().withUnsafeMutableBufferPointer { (p: UnsafeMutableBufferPointer<UInt8>) in
    print(p, p.count)
    p.forEach { print($0) }
}

打印

UnsafeMutableBufferPointer(start: 0x000000010300e100, count: 4) 4
1, 2, 3, 4

请参阅UnsafeRawPointer MigrationSE-0107 了解更多信息。

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    相关资源
    最近更新 更多