[swift-users] What is "binding" memory?
Rien
Rien at Balancingrock.nl
Wed Nov 2 12:37:05 CDT 2016
> On 02 Nov 2016, at 18:07, Manfred Schubert via swift-users <swift-users at swift.org> wrote:
>
> 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?
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.
Rien.
>
>> 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?
>
>
> Manfred
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
More information about the swift-users
mailing list