How to use UnsafeMutableBufferPointer

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 saw UnsafeMutablePointer which was used as

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

How to use UnsafeMutableBufferPointer for C style buffer in Swift? Also, how would I redistribute more space for a pointer?

+4
source share
1 answer

UnsafeMutableBufferPointerdoesn't have its own memory, so you still have to use it UnsafeMutablePointerto allocate base memory. But then you can use the buffer pointer as a collection and enumerate it with 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 arrows do not provide functionality realloc. You can use the C functions or roll yourself if you want.

+6
source

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


All Articles