[swift-users] Pointer conversions between different sockaddr types
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
But this migration guide is more approachable… it’s still WIP:
>> - 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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-users