[swift-users] Guarantees of Tuples as Fixed Sized (stack allocated) Arrays

Martin R martinr448 at gmail.com
Fri Apr 28 06:59:43 CDT 2017


As far as I know, the only guarantee is made for structures imported from C. From https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160516/001968.html <https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160516/001968.html> :

   Swift structs have unspecified layout. If you depend on a specific layout, you should define the struct in C and import it into Swift for now.

and from https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160516/001980.html <https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160516/001980.html> :

   That's not necessary. You can leave the struct defined in C and import it into Swift. Swift will respect C's layout.

Regards, Martin


> On 28. Apr 2017, at 13:03, Johannes Weiss via swift-users <swift-users at swift.org> wrote:
> 
> Hi swift-users,
> 
> (sorry for the cross post to swift-dev, but wasn't sure where it belongs)
> 
> I tried to find guarantees about the memory layout Swift tuples but couldn't find anything. The reason I ask is because I'd like to use them as fixed sized (stack allocated) arrays. I'm pretty sure they're actually not guaranteed to be stack allocated but highly likely I assume :).
> 
> Am I correct in assuming that
> 
>    let swift_events: (kevent, kevent) = ...
> 
> has the same memory layout as
> 
>    struct kevent c_events[2] = ...
> 
> ? In other words, is this legal:
> 
>    var events = (kevent(), kevent())
>    withUnsafeMutableBytes(of: &events) { event_ptr in
>        precondition(MemoryLayout<kevent>.size * 2 == event_ptr.count)
>        if let ptr = event_ptr.baseAddress?.bindMemory(to: kevent.self, capacity: 2) {
>            return kevent(someFileDescriptor, ptr, 2, ptr, 2, nil)
>        }
>    }
> 
> I'm assuming yes but I'd like to make sure.
> 
> Many thanks,
>  Johannes
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


More information about the swift-users mailing list