calloc in Swift

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

How do I transform the following ObjectiveC statements into SWIFT:

UInt32 *pixels; pixels = (UInt32 *) calloc(height * width, sizeof(UInt32));

I tried to do the following:

var pixels: UInt32 pixels = (UInt32)calloc(height * width, sizeof(UInt32))

and I receive the error message:

Int is not convertible to UInt

and the (UInt32) Casting didn't work as well. Can someone give me some advice please? I am struggling a little bit with SWIFT still. Thank you.

回答1:

Here's an easier way of allocating that array in swift:

var pixels = [UInt32](count: height * width, repeatedValue: 0)

If that's what you actually want to do.

But, if you need a pointer from calloc for some reason, go with:

let pixels = calloc(UInt(height * width), UInt(sizeof(UInt32)))

The type of pixels though must be a type of UnsafeMutablePointer<T>, and you would handle it like a swift pointer in the rest of your code.



回答2:

If you really know what you are doing and insist in allocating memory unsafely using calloc:

var pixels: UnsafeMutablePointer<UInt32> pixels = calloc(height * width, sizeof(UInt32))

or just

var pixels = calloc(height * width, sizeof(UInt32))


回答3:

For Swift-3 : UnsafeMutablePointer is replace by UnsafeMutableRawPointer

 var pixels = UnsafeMutableRawPointer( calloc(height * width, MemoryLayout<UInt32>.size) )

Reference



转载请标明出处:calloc in Swift
文章来源: calloc in Swift
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!