swift3 - How to migrate array.withUnsafeMutableBufferPointer from swift 2 to swift 3? -
i want use code this link in 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 }
a class implemented above protocol:
final public class sglimagergba8 : sglimagetype { ... public func withunsafemutablebufferpointer(@noescape body: (unsafemutablebufferpointer<uint8>) throws -> void) rethrows { try array.withunsafemutablebufferpointer(){ // unsafe reinterpret cast. careful here. let st = unsafemutablepointer<uint8>($0.baseaddress) try body(unsafemutablebufferpointer<uint8>(start: st, count: $0.count*channels)) } }
in swift 3, line let st = unsafemutablepointer<uint8>($0.baseaddress)
throws error:
'init' unavailable: use 'withmemoryrebound(to:capacity:_)' temporarily view memory layout-compatible type
how resolve error?
you convert unsafemutablebufferpointer<uint8>
unsafemutablerawbufferpointer
, bind uint8
, create unsafemutablebufferpointer<uint8>
(using dummy values here properties):
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) } }
prints
unsafemutablebufferpointer(start: 0x000000010300e100, count: 4) 4 1, 2, 3, 4
see unsaferawpointer migration , se-0107 more information.
Comments
Post a Comment