Guarantees of Tuples as Fixed Sized (stack allocated) Arrays

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 :).

Tuples are guaranteed to use a standard C-style layout wherever that layout is ABI-observable, e.g. when you construct an UnsafePointer to one.

Note that that layout isn't ABI-observable when the tuple is, say, just stored in a struct. The compiler is allowed to break up the tuple and store its components however it likes. Of course, if the compiler does that, and you turn around and construct an UnsafePointer to that property, then the compiler has to reconstitute the tuple into an ABI-compliant temporary that it can give you a pointer to; this is yet another reason why you can't maintain permanent unsafe pointers to components of a struct.

John.

···

On Apr 28, 2017, at 7:03 AM, Johannes Weiss via swift-dev <swift-dev@swift.org> wrote:

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-dev mailing list
swift-dev@swift.org
https://lists.swift.org/mailman/listinfo/swift-dev