> On Nov 3, 2016, at 7:16 AM, Manfred Schubert via swift-users 
> <swift-users@swift.org> wrote:
> 
> 
>> Am 02.11.2016 um 18:37 schrieb Rien <r...@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@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to