Search code examples
iospointersswiftdereference

Swift pointer arithmetic and dereferencing; converting some C-like map code to Swift


I have this little bit of Swift code that does not seem to be working...

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

A Room is part of a stab at a roguelike game if you're curious. I'm trying to rewrite a couple of parts in Swift. Here's the code that appears broken, and what I hope I am doing 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 the value of pointValue is not what I know I am looking at on the map, having set a very simple location (1, 1) to a known value. It seems pretty obvious that Swift is not supposed to be doing this kind of thing but it's a conversion with the aim of learning the Way of Swift when I know the syntax well enough.

I expect the error is in the swift code - since this was all working in the objective C version. Where's the error?


Solution

  • You are assigning locationPointer to point to the new location, but still using ptr in the next line, and the value of ptr has not been changed. Change your last line to:

    var pointValue = locationPointer.memory
    

    or you could change your pointer to a 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