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

Andrew Trick atrick at apple.com
Thu Nov 3 23:45:12 CDT 2016


> On Nov 3, 2016, at 7:16 AM, Manfred Schubert via swift-users <swift-users at swift.org> wrote:
> 
> 
>> 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.

Yes, this would work

  withMemoryRebound(to: UInt16.self, capacity: 1) { print($0.pointee) }

So would this

  rawPtr.bindMemory(to: Int16.self, capacity: 1)
  print(widePtr.pointee)

Or this

  rawPtr.load(as: UInt16.self)

-Andy

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