Arithmetic of fast pointers and dereferencing; converting some C-like map code to Swift

I have some Swift code that doesn't seem to work ...

// earlier, in Obj C... typedef struct _Room { uint8_t *map; int width; int height; } Room; 

The room is part of the kick in the game with roguelike, if you're interested. I am trying to rewrite a couple of parts in Swift. Here's a code that looks broken, and what I hope I do as comments:

 let ptr = UnsafePointer<UInt8>(room.map) // grab a pointer to the map out of the room struct let offset = (Int(room.width) * Int(point.y)) + Int(point.x) // calculate an int offset to the location I am interested in examining let locationPointer = ptr + offset // pointer advances to point to the offset I want var pointValue = ptr.memory // What I used to get with *ptr 

Something is wrong here, because simple tests show that the pointValue value is not what I know, I look at the map by setting a very simple location (1, 1) to a known value. It seems pretty obvious that Swift shouldn't do this kind of thing, but it's a conversion to learn Way of Swift when I know the syntax well.

I expect the error is indicated in the quick code, as it all worked in the objective version of C. Where is the error?

+6
source share
1 answer

You assign locationPointer to point to the new location, but still use ptr in the next line, and the ptr value has not been changed. Change your last line to:

 var pointValue = locationPointer.memory 

or you can change the pointer to var and advance it:

 var ptr = UnsafePointer<UInt8>(room.map) // grab a pointer to the map out of the room struct let offset = (Int(room.width) * Int(point.y)) + Int(point.x) // calculate an int offset to the location I am interested in examining ptr = ptr + offset // pointer advances to point to the offset I want var pointValue = ptr.memory // What I used to get with *ptr 
+10
source

Source: https://habr.com/ru/post/975253/


All Articles