[swift-users] Pointer conversions between different sockaddr types

Andrew Trick atrick at apple.com
Fri Aug 19 12:58:18 CDT 2016


> On Aug 18, 2016, at 12:28 AM, Quinn The Eskimo! via swift-users <swift-users at swift.org> wrote:
> 
> 
> On 17 Aug 2016, at 18:55, Martin R via swift-users <swift-users at swift.org> wrote:
> 
>> - Are both solutions correct, should one be preferred, or are both wrong?
> 
> Your `withMemoryRebound` solution is correct.

Absolutely, withMemoryRebound is always safe. You can use it whenever you just need to reinterpret memory at a call site and know the number of values stored that memory location. In this case it’s “easy" because you’re dealing a single sockaddr_in.

The UnsafeRawPointer proposal is the definitive reference
https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md <https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md>

But this migration guide is more approachable… it’s still WIP:
https://gist.github.com/atrick/0283ae0e284610fd21ad6ed3f454a585

>> - Can the same be achieved simpler?
> 
> Not without introducing a layer of abstraction.
> 
> In my case I introduced an abstract `Address` type (basically a wrapper around `sockaddr_storage`) and then added a method to that object which calls a closure with the right parameters (actually, multiple such methods, depending on whether I’m calling something like `connect` which takes an address, or `getpeername`, which returns one).  This approach concentrates all the ugly in one place, making the rest of my BSD Sockets code much cleaner.

This is an annoying UpdatePointer migration case because it falls under the category of misbehaving C APIs that we deliberately don't want to encourage in Swift.

The only good answer is to provide a Swift wrapper on top of the socket API as Quinn has done. It would be nice to post that code at some point so users of the socket API can copy-paste into their project.

-Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160819/f527810c/attachment.html>


More information about the swift-users mailing list