2016-01-12 52 views
4

在C我會做這樣的事情如何使用UnsafeMutableBufferPointer

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

我見過UnsafeMutablePointer像這樣使用

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

如何使用UnsafeMutableBufferPointer在斯威夫特一個C風格的緩衝?另外,我將如何爲指針重新分配更多空間?

回答

6

UnsafeMutableBufferPointer不擁有它的內存,所以你仍然必須使用UnsafeMutablePointer來分配底層內存。但是,您可以使用緩衝區指針作爲集合,並使用for-in循環來枚舉它。

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! 

斯威夫特指針不提供realloc功能。你可以使用C函數,或者如果你想這樣做,你可以推出自己的函數。

+0

嗨Khadpe,我有幾天的相對問題,請幫忙:http://stackoverflow.com/questions/36662378/testcase-failed-after-converting-codes-from-objective-c-to-swift –