Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: fill data into unsafeMutablePointer of UInt8 type doesn't work

Tags:

swift

I have the following code which doesn't work. How can I fill in data into the memory block of UnsafeMutablePointer? The bufferSize is 1024. I tried to fill 0, 1, 2...1023 into the buffer.

let pbuffer = UnsafeMutablePointer<UInt8>.alloc(bufferSize)

for index in 0...bufferSize - 1 
{

    pbuffer[index] = UInt8(index)

}

Thank you!

like image 338
Nicole Avatar asked Sep 23 '14 18:09

Nicole


1 Answers

Your problem is not the UnsafeMutablePointer, but rather that you're trying to initialize a UInt8 with a value that won't fit in it; UInt8 has a maximum value of 255. So, up to a bufferSize of 256, your code will work fine; beyond that, it'll crash.

All you need to do to fix this is use a different type for your UnsafeMutablePointer. If you want to go up to a bufferSize of 1024, a UInt16 will work fine (max value 65535):

let bufferSize = 1024
let pbuffer = UnsafeMutablePointer<UInt16>.alloc(bufferSize)

for index in 0..<bufferSize
{
    pbuffer[index] = UInt16(index)
}
like image 163
Mike S Avatar answered Oct 04 '22 21:10

Mike S