Swift: It is not possible to convert a value of type UnsafeMutablePointer to the expected argument type "UnsafeMutablePointer"

I have a little problem with my code after upgrading to Swift 3. I had this code before the conversion:

extension NSData { func castToCPointer<T>() -> T { let mem = UnsafeMutablePointer<T>.alloc(sizeof(T.Type)) self.getBytes(mem, length: sizeof(T.Type)) return mem.move() } } 

And I converted it to this code, and in the third line I get an error

... It is not possible to convert a value of type UnsafeMutablePointer to the expected type of the argument "UnsafeMutablePointer"

 extension Data { func castToCPointer<T>() -> T{ let mem = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T.Type>.size) self.copyBytes(to: mem, count: MemoryLayout<T.Type>.size) //self.copyBytes(to: mem, count: MemoryLayout<T.Type>.size) return mem.move() } } 

Does anyone know how to get rid of this?

+6
source share
2 answers

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 } } } 
+5
source

You can also use the syntax below in the extension

 extension Data { func castToCPointer<T>() -> T { var bytes = self.bytes var val = withUnsafePointer(to: &bytes) { (temp) in return unsafeBitCast(temp, to: T.self) } return val } } 

 var data:NSData/NSMutableData var bytes = data.bytes var val = withUnsafePointer(to: &bytes) { (temp) in return unsafeBitCast(temp, to: T.self) } 
0
source

Source: https://habr.com/ru/post/1011941/


All Articles