0

The function below does not compile in Swift 3.

func sockaddr_cast(p: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<sockaddr> {
    return UnsafeMutablePointer<sockaddr>(p)
}

It generates the following error:

Cannot invoke initializer for type 'UnsafeMutablePointer' with an argument list of type '(UnsafeMutableRawPointer)'

What's the Swift 3 version of this code?

This question seems similar, but the answer didn't help.

Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • 1
    You have to "rebind" the pointer, see https://stackoverflow.com/a/45564264/1187415 for an example. – Martin R Jan 25 '18 at 08:54
  • @MartinR thanks! Changing `return UnsafeMutablePointer(p)` => `return withUnsafePointer(to: &p)` yields this error: `Cannot pass immutable value as inout argument: 'p' is a 'let' constant` ... how can you rebind if the pointer cannot be made as an inout argument? – Crashalot Jan 25 '18 at 09:20
  • The immediate translation would be `return p.withMemoryRebound(to: sockaddr.self, capacity: 1) { $0 }` , however, that is unsafe because the rebound pointer is only valid during the execution of the closure and should not be passed to the outside. So there is no safe way in Swift 3 to "just cast" the pointer, you _temporarily_ rebind it (as in https://stackoverflow.com/a/45564264/1187415). See also https://swift.org/migration-guide-swift3/se-0107-migrate.html, which has several sockaddr examples. – Martin R Jan 25 '18 at 09:27

0 Answers0