calloc in Swift

前端 未结 3 1601
余生分开走
余生分开走 2021-01-13 17:10

How do I transform the following ObjectiveC statements into SWIFT:

UInt32 *pixels;
pixels = (UInt32 *) calloc(height * width, sizeof(UInt32));
相关标签:
3条回答
  • 2021-01-13 17:20

    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))
    
    0 讨论(0)
  • 2021-01-13 17:21

    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.

    0 讨论(0)
  • 2021-01-13 17:41

    For Swift-3 : UnsafeMutablePointer is replace by UnsafeMutableRawPointer

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

    Reference

    0 讨论(0)
提交回复
热议问题