arraysswiftunsafemutablepointer

Swift array as c function buffer


I'm using swift array as output buffer for a function that takes a pointer and fills it, like this:

var buffer : [Int32] = ...
tehFillFunc(UnsafeMutablePointer<Int32>(buffer))

This works fine, the problem is that compiler is complaining that Variable 'buffer' was never mutated; consider changing to 'let' constant, which I don't want to do as I'm pretty sure it was mutated in my fill function.

So, is there a way to silence it? (I could just do some dummy set, but I'd prefer to do it properly).

Edit: As requested complete example code that shows the problem (c is not even necessary):

class ViewController: UIViewController {

    func fill(sth: UnsafeMutablePointer<Int32>) {
        sth[0] = 7
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var array = [Int32].init(count: 10, repeatedValue: 0)
        fill(UnsafeMutablePointer<Int32>(array))
        print("\(array)")
    }
}

However, the solution was already posted. In simplest form:

        fill(&array)

Solution

  • Usually you need to have specify buffer size. And in this case I prefer following solution:

    let bufferSize = 1000
    var buffer = [Int32](count: bufferSize, repeatedValue: 0)
    tehFillFunc(&buffer)