Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UnsafeMutableBufferPointer

Tags:

swift

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?

like image 928
joels Avatar asked Jan 12 '16 17:01

joels


People also ask

What is UnsafePointer?

UnsafePointer provides no automated memory management or alignment guarantees. You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior. Memory that you manually manage can be either untyped or bound to a specific type.

Does Swift have pointers?

Swift's typed pointers give you direct access to memory, but only within the confines of type safety. You can't have two typed pointers to the same memory that disagree on the type. So, if your goal is to reinterpret bytes of memory as different types, then you need use a lower-level API.


1 Answers

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.

like image 66
Marc Khadpe Avatar answered Nov 16 '22 00:11

Marc Khadpe