2017-04-08 67 views
1

我試圖在swift中轉換Objective-C代碼,並且我完全被阻止,尋找一種方法來獲取Pixel_8緩衝區(我通常在物鏡中使用calloc創建-c)。如何在swift中創建Pixel_8緩衝區

以下是Objective-c中的一個示例...它如何轉換爲swift?

Pixel_8 *buffer = (Pixel_8 *)calloc(width*height, sizeof(Pixel_8)); 
+0

你用這種方式嘗試'var buffer:Pixel_8? =(calloc(width * height,MemoryLayout .size)as?Pixel_8)'或'var buffer =(calloc(width * height,sizeof(Pixel_8))as!Pixel_8) ' –

回答

2

可以在斯威夫特用calloc(),但你必須到原始 指針 「綁定」 到想要的類型:

let buffer = calloc(width * height, MemoryLayout<Pixel_8>.stride).assumingMemoryBound(to: Pixel_8.self) 

// Use buffer ... 

free(buffer) 

或者:

let buffer = UnsafeMutablePointer<Pixel_8>.allocate(capacity: width * height) 
buffer.initialize(to: 0, count: width * height) 

// Use buffer ... 

buffer.deinitialize() 
buffer.deallocate(capacity: width * height) 

但最簡單的解決方案是分配一個Swift數組:

var buffer = [Pixel_8](repeating: 0, count: width * height) 

這是自動進行內存管理。你可以通過buffer到 任何函數期望UnsafePointer<Pixel_8>或 通過&buffer任何函數期望UnsafeMutablePointer<Pixel_8>

0

用這種方式試圖

宣言

typealias Pixel_8 = UInt8 

swift3

var buffer: Pixel_8? = (calloc(width * height, MemoryLayout<Pixel_8>.size) as? Pixel_8) 

swift2

var buffer = (calloc(width * height, sizeof(Pixel_8)) as! Pixel_8) 

Apple API reference

+0

Pixel_8已經被定義。無論如何,我得到這個錯誤:'不能轉換Pixel_8類型的值?到期望的參數類型UnsafeMutableRowPointer!' – MatterGoal

相關問題