copyBytes
expects a UnsafeMutableBufferPointer
as an argument:
extension Data { func castToCPointer<T>() -> T { let mem = UnsafeMutablePointer<T>.allocate(capacity: 1) _ = self.copyBytes(to: UnsafeMutableBufferPointer(start: mem, count: 1)) return mem.move() } }
( allocate()
takes the number of "elements" as an argument, not the number of bytes.)
But note that your method of leaking memory allocated memory is uninitialized (with move()
), but should also be redistributed:
extension Data { func castToCPointer<T>() -> T { let mem = UnsafeMutablePointer<T>.allocate(capacity: 1) _ = self.copyBytes(to: UnsafeMutableBufferPointer(start: mem, count: 1)) let val = mem.move() mem.deallocate(capacity: 1) return val } }
A simpler solution would be (from round business cards Swift data types to / from data ):
extension Data { func castToCPointer<T>() -> T { return self.withUnsafeBytes { $0.pointee } } }
source share