[swift-users] Can I use a tuple to force a certain memory layout?

Taylor Swift kelvin13ma at gmail.com
Thu Jul 20 11:41:54 CDT 2017


Does addressof count as legally observing it?

        var buffers:(GL.UInt, GL.UInt) = (0, 0)
        glGenBuffers(n: 2, buffers: &buffers.0)

Also, I assume Swift performs a swizzle if the tuple is defined in a
separate module from where the pointer to it is constructed?

On Thu, Jul 20, 2017 at 4:59 AM, Johannes Weiß <johannesweiss at apple.com>
wrote:

> When you can (legally) observe it, tuples in Swift have guaranteed
> standard C-style layout.
>
> John McCall confirms this here: https://lists.swift.org/
> pipermail/swift-dev/Week-of-Mon-20170424/004481.html
>
> > On 20 Jul 2017, at 4:33 am, Taylor Swift via swift-users <
> swift-users at swift.org> wrote:
> >
> > Many APIs like OpenGL take arrays where the atomic unit is multiple
> elements long. For example, a buffer of coordinates laid out like
> >
> > :[Float] = [ x1, y1, z1, x2, y2, z2, ... , xn, yn, zn ]
> >
> > I want to be able to define in Swift (i.e., without creating and
> importing a Objective C module) a struct that preserves the layout, so that
> I can do withMemoryRebound(to:capacity:_) or something similar and treat
> the buffer as
> >
> > struct Point
> > {
> >     let x:Float,
> >         y:Float,
> >         z:Float
> > }
> >
> > :[Point] = [ point1, point2, ... , pointn ]
> >
> > The memory layout of the struct isn’t guaranteed, but will the layout be
> guaranteed to be in declaration order if I use a tuple inside the struct
> instead?
> >
> > struct Point
> > {
> >     let _point:(x:Float, y:Float, z:Float)
> >
> >     var x:Float
> >     {
> >         return self._point.x
> >     }
> >
> >     var y:Float
> >     {
> >         return self._point.y
> >     }
> >
> >     var z:Float
> >     {
> >         return self._point.z
> >     }
> > }
> >
> > This is an ugly workaround, but I can’t really think of any alternatives
> that don’t involve “import something from Objective C”. I am aware that the
> implementation of structs currently lays them out in declaration order, but
> I’m looking for something that’s actually defined in the language.
> >
> >
> > _______________________________________________
> > 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/20170720/a66fd0e8/attachment.html>


More information about the swift-users mailing list