[swift-evolution] [RFC] UnsafeBytePointer API for In-Memory Layout

Joe Groff jgroff at apple.com
Mon May 9 15:16:54 CDT 2016


> On May 9, 2016, at 12:38 PM, Geordie Jay via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I read this proposal and I'm a bit unsure what its purpose would be:
> 
> Basically you want to prevent UnsafePointer<XYZ>(UnsafePointer<Void>) conversions and/or vice-versa? And you'd achieve this by replacing UnsafePointer<Void> with UnsafeBytePointer that has no bound pointer type?
> 
> In one sense the change seems fine to me, but as someone who uses a lot of C APIs and a lot of CoreAudio/CoreMIDI in Swift already I can't really see what benefit it'd bring. Presumably we'd still want an option of converting UnsafeBytePointer to UnsafePointer<SomeActualType> for things like C function pointer callback "context"/"userInfo" uses, so it's not like we'd be preventing programmer error in that way.
> 
> Call me conservative but to me the current system seems to work as well as it can. If anything it's already enough boilerplate going through hoops converting an UnsafeMutablePointer<Void> into a [Float] even when I know and the C API knows perfectly well what it actually contains... Would happily be convinced otherwise about this proposal though, I'm pretty new at all this.
> 
> Geordie

> On May 9, 2016, at 12:57 PM, Guillaume Lessard via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I’m sympathetic to the elimination of UnsafePointer<Void> as general shorthand for an arbitrary pointer, but I lose the plot of this very long proposal. It seems to me that this increases API surface, yet everything I could do before, I could still do; it just involves more typing. What exactly does this make better?
> 
> Cheers,
> Guillaume Lessard

Andy, I think it's worth clarifying the primary purpose of this proposal. Our main goal here is to provide a legal means for "type-punning" memory access. Like C and C++, it's technically undefined behavior in Swift to cast an UnsafePointer<T> to an UnsafePointer<U> of a different type and load a value out of memory that's of a different type from what was stored there. We don't take much advantage of this yet in Swift's optimizer, since we don't have good alternative API. UnsafeBytePointer seeks to fill this gap by providing a type that can safely do type-punned loads and stores.

-Joe


More information about the swift-evolution mailing list