[swift-users] What is "binding" memory?
Manfred Schubert
dev at schubert-it.com
Thu Nov 3 09:16:37 CDT 2016
> Am 02.11.2016 um 18:37 schrieb Rien <Rien at Balancingrock.nl>:
>
>>>
>>> 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.
If I understand the documentation correctly, this should not be allowed, because it’s not allowed to access memory as different types at the same time. It needs to be „bound“ to the type first, and can only be bound to one type at a time, so all access as another type must be encapsulated within a closure.
Manfred
More information about the swift-users
mailing list