> On Nov 2, 2016, at 10:37 AM, Rien via swift-users <swift-users@swift.org> 
> wrote:
> 
>>> 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.

Allowing type punning is one of the main purposes of raw memory access (via a 
raw pointer). But in this code, widePtr.pointee is a typed UInt16 load from 
memory that is bound to UInt8. Loading a UInt16 without rebinding memory first 
requires a raw load such as:

rawPtr.load(as: UInt16.self)

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

Reply via email to