2017-04-14 101 views
1

我想從this link 這是在SWIF使用代碼2如何將array.withUnsafeMutableBufferPointer從swift 2遷移到swift 3?

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)) 
    } 
} 
在迅速3

,線let st = UnsafeMutablePointer<UInt8>($0.baseAddress)引發此錯誤:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type

如何解決此錯誤?

+0

可能重複[Swift 3 UnsafePointer($ 0)不再在Xcode 8 beta 6中編譯](http://stackoverflow.com/questions/39046377/swift-3-unsafepointer0-no-longer-compile-in-xcode -8-beta-6) – kennytm

+0

@kennytm其不重複的。 – xaled

回答

1

您可以在UnsafeMutableBufferPointer<UInt8>轉換爲UnsafeMutableRawBufferPointer,綁定,爲UInt8,並創建從一個UnsafeMutableBufferPointer<UInt8>(這裏使用虛擬值的所有屬性):

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瞭解更多信息。