Correct way to call “realloc” in Swift with a Float array?

元气小坏坏 提交于 2019-12-05 02:23:25

问题


I'm trying figure out what size to send "realloc" when I call it through Swift. It seems that I have to add an extra byte, but I don't understand why.

typealias Floats = UnsafeMutablePointer<Float>

let FLOAT_SIZE = sizeof( Float )

func floats_realloc( floats:Floats, qty_of_floats:Int ) -> Floats  {

     let KLUDGE = 1 // Why?

     let qty_of_bytes = ( qty_of_floats * FLOAT_SIZE ) + KLUDGE

     let realloced_floats = Floats(

          realloc( floats, UInt( qty_of_bytes ) )

     )

     return realloced_floats

}

If I set KLUDGE to 0 here, this is what happens when I attempt to make room for one new member in a three member array:

In: [0.9, 0.9, 0.9]

Out: [0.0, 0.0, 0.9, 0.0]

What I would expect is:

Out: [0.9, 0.9, 0.9, 0.0]

The arrays I'm sending it are created within Swift, using

var foo_floats = Floats.alloc(QTY_OF_FLOATS)

What's wrong with my call to realloc?


回答1:


I've discussed this on Apple's Developer Forum. It turns out that using Swift's alloc allots space for a Swift array, not a C array. So if you want to use MutableUnsafePointer for a C array and "realloc" (bridged from C) you need to stick with C functions, like "malloc" (bridged from C).

By adding the following function, and using it when I initially set up my Floats array, the "realloc" bug went away:

func floats_alloc( qty_of_floats:Int ) -> Floats  {

      // return Floats.alloc( qty_of_floats )

      let qty_of_bytes = ( qty_of_floats * FLOAT_SIZE )

      let alloced_floats = Floats(

           malloc( UInt( qty_of_bytes ) )

      )

      return alloced_floats

 }

I've tested for a couple weeks now, and all is well.



来源:https://stackoverflow.com/questions/24981124/correct-way-to-call-realloc-in-swift-with-a-float-array

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