9

In C I would do something like this

int count = 10;
int *buffer;
num = malloc(count * sizeof(int));
for (int i = 0; i < count; i++) {
    buffer[i] = rand();
}

I have seen UnsafeMutablePointer used like this

let buffer = UnsafeMutablePointer<Int>.alloc(count)
for i in 0..<count {
    buffer[i] = Int(arc4random())
}

How do I use UnsafeMutableBufferPointer for a C style buffer in Swift? Also, how would I realloc more space for the pointer?

joels
  • 7,249
  • 11
  • 53
  • 94

1 Answers1

14

UnsafeMutableBufferPointer doesn't own its memory, so you still have to use UnsafeMutablePointer to allocate the underlying memory. But then you can use the buffer pointer as a collection, and enumerate it using for-in loops.

let count = 50
let ptr = UnsafeMutablePointer<Int>.alloc(count)
let buffer = UnsafeMutableBufferPointer(start: ptr, count: count)
for (i, _) in buffer.enumerate() {
    buffer[i] = Int(arc4random())
}

// Do stuff...

ptr.dealloc(count)   // Don't forget to dealloc!

Swift pointers don't provide realloc functionality. You could use the C functions, or roll your own if you want do that.

Marc Khadpe
  • 2,012
  • 16
  • 14
  • Hi Khadpe, I have a relative question for several days, please help: http://stackoverflow.com/questions/36662378/testcase-failed-after-converting-codes-from-objective-c-to-swift – Zigii Wong Apr 20 '16 at 09:10