[swift-users] What is "binding" memory?

Andrew Trick atrick at apple.com
Thu Nov 3 23:41:03 CDT 2016

> On Nov 2, 2016, at 10:37 AM, Rien via swift-users <swift-users at swift.org> wrote:
>>> var rawPtr = UnsafeMutableRawPointer.allocate(bytes: 2, alignedTo: 0)
>>> var widePtr = rawPtr.bindMemory(to: Int16.self, capacity: 1)
>>> widePtr.pointee = 32
>>> var narrowPtr = rawPtr.bindMemory(to: UInt8.self, capacity: 2)
>>> narrowPtr[0] = 16
>>> narrowPtr[1] = 255
>>> print(widePtr.pointee)
>> This compiles and runs as expected, but it should not be allowed if I understand things correctly. So shouldn’t it be a compile time error or crash at runtime? If not, what do I get over how it was before where I was casting to a typed pointer?
> Why do you think it should not be allowed.
> AFAICS everything is correct.
> Are you referring to the multiple interpretation of the raw memory? That is entirely intentional, indeed one of the main purposes.

Allowing type punning is one of the main purposes of raw memory access (via a raw pointer). But in this code, widePtr.pointee is a typed UInt16 load from memory that is bound to UInt8. Loading a UInt16 without rebinding memory first requires a raw load such as:

rawPtr.load(as: UInt16.self)

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

More information about the swift-users mailing list