本文介绍了调用“realloc"的正确方法在带有 Float 数组的 Swift 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过 Swift 调用realloc"时,我正在尝试确定要发送的大小.看来我必须添加一个额外的字节,但我不明白为什么.

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

}

如果我在这里将 KLUDGE 设置为 0,那么当我尝试为三成员数组中的一个新成员腾出空间时会发生这种情况:

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:

输入:[0.9, 0.9, 0.9]

输出:[0.0, 0.0, 0.9, 0.0]

我期望的是:

输出:[0.9, 0.9, 0.9, 0.0]

我发送的数组是在 Swift 中创建的,使用

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

var foo_floats = Floats.alloc(QTY_OF_FLOATS)

我对 realloc 的调用有什么问题?

What's wrong with my call to realloc?

推荐答案

我已经在 Apple 的开发者论坛上讨论过这个问题.事实证明,使用 Swift 的 alloc 为 Swift 数组分配空间,而不是 C 数组.因此,如果您想将 MutableUnsafePointer 用于 C 数组和realloc"(从 C 桥接),您需要坚持使用 C 函数,例如malloc"(从 C 桥接).

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).

通过添加以下函数,并在我最初设置我的 Floats 数组时使用它,realloc"错误消失了:

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.

这篇关于调用“realloc"的正确方法在带有 Float 数组的 Swift 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:07
查看更多