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

Rien Rien at Balancingrock.nl
Thu Nov 3 09:41:08 CDT 2016


> On 03 Nov 2016, at 15:16, 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.
> 

Ah, but that is not the case.

It is important to differentiate between the “gateway” to the memory and the memory area itself.
Different programming languages/compilers have different approaches, but I believe that Swift allocates a struct for every gateway.
widePtr and narrowPtr are two different gateways. They refer to different struct's. But the struct for each of them refers to the same memory area.

Example: widePtr can be located at address 0x1000, narrowPtr can be allocated at address 0x2000 while the memory area both refer to (the raw memory) can be at address 0x3000

Every access to the raw memory via a gateway must follow the rules for that gateway.

Note: Some compilers may only create ephemeral gateways, but as long as the compiler checks that the acces follows the correct rules, that is not a problem.

This is not only very useful, but it also opens the door to better interfaces to some low level Unix APIs.


> 
> Manfred
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

Regards,
Rien

Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Swiftrien
Project: http://swiftfire.nl




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161103/0473aecd/attachment.html>


More information about the swift-users mailing list