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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With