Search code examples
iosswiftunsafemutablepointer

How to print pointer contents in Swift


I am trying to print contents of pointer pointed to by a raw pointer but when I print or NSLog, I get the value of pointer than the contents of memory pointed to by pointer. How do I print contents of memory pointed to by pointer? Below is my code:

    let buffer = unsafeBitCast(baseAddress, to: UnsafeMutablePointer<UInt32>.self)
     for row in 0..<bufferHeight
    {
        var pixel = buffer + row * bytesPerRow

        for _ in 0..<bufferWidth {
           // NSLog("Pixel \(pixel)")
            print(pixel)
            pixel = pixel + kBytesPerPixel
        }
    }

Solution

  • pixel is a pointer to an UInt32, in order to print the pointed-to value you have to dereference it:

    print(pixel.pointee)
    

    Note that incrementing a pointer is done in units of the stride of the pointed-to value, so your

    pixel = pixel + kBytesPerPixel
    

    will increment the address by 4 * kBytesPerPixel bytes, which may not be what you intend.