Swift 中的 calloc [英] calloc in Swift

查看:79
本文介绍了Swift 中的 calloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下 ObjectiveC 语句转换为 SWIFT:

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

我尝试执行以下操作:

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

然后我收到错误消息:

<块引用>

Int 不能转换为 UInt

和 (UInt32) Casting 也不起作用.有人可以给我一些建议吗?我仍然在用 SWIFT 苦苦挣扎.谢谢.

解决方案

这里有一种更简单的快速分配数组的方法:

var pixel = [UInt32](count: height * width, repeatValue: 0)

如果这就是您真正想做的事情.

但是,如果您出于某种原因需要来自 calloc 的指针,请使用:

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

pixels 的类型虽然必须是 UnsafeMutablePointer<T> 的类型,并且您可以像处理其余代码中的 swift 指针一样处理它.>

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.

解决方案

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.

这篇关于Swift 中的 calloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆