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

Manfred Schubert dev at schubert-it.com
Wed Nov 2 12:07:41 CDT 2016

Am 01.11.2016 um 21:40 schrieb Andrew Trick <atrick at apple.com>:
> I’m not sure I like the “prepares the memory” language myself. Binding memory communicates to the compiler that the memory locations are safe for typed access. Nothing happens at runtime--until someone writes a type safety sanitizer.

So nothing happens at runtime, and also nothing appears to happen at compile time. If I try this code:

> 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?

> It affects the abstract state of the memory location, independent of the pointer variable used to access that memory. Binding memory returns a typed pointer for convenience and clarity, but there’s nothing special about that particular pointer value.

If it were not returning a typed pointer, what would it actually do?


More information about the swift-users mailing list