[swift-users] [swift-dev] Guarantees of Tuples as Fixed Sized (stack allocated) Arrays
Johannes Weiss
johannesweiss at apple.com
Tue May 2 06:04:50 CDT 2017
Thanks very much John, that's what I expected and hoped for as it's enough to call kevent() for a (kevent_t, kevent_t) used as struct kevent[2] .
> On 29 Apr 2017, at 00:28, John McCall <rjmccall at apple.com> wrote:
>
>> On Apr 28, 2017, at 7:03 AM, Johannes Weiss via swift-dev <swift-dev 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 :).
>
> 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.
>
>>
>> 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 at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-dev
More information about the swift-users
mailing list