Search code examples
swiftunsafemutablepointer

Realloc UnsafeMutablePointer in Swift cause error


I am converting some operations about C pointer to Swift.

var bits = UnsafeMutableBufferPointer<Int32>(start: nil, count: 0)

var startIdx: UnsafeMutablePointer<Int32> = nil {
    didSet {
        bits = UnsafeMutableBufferPointer<Int32>(start: startIdx, count: bitsLength)
        defer { bits.baseAddress.dealloc(bits.count) }
    }
}

var size: Int = 0
var bitsLength: Int = 1

init(size: Int) {
    self.size = size
    self.bitsLength = (size + 31) / 32
    self.startIdx = UnsafeMutablePointer<Int32>.alloc(bitsLength * sizeof(Int32))
}

func ensureCapacity(size: Int) {
    if size > bitsLength * 32 {
        let newBitsLength = (size + 31) / 32

        startIdx = realloc(startIdx, sizeof(Int32) * newBitsLength) 
        // Cannot convert value of type `UnsafeMutablePointer<Int32>` to type 'UnsafeMutablePointer<Void>'(aka `UnsafeMutablePointer<()>`) in coercion
    }
}

I got this

Cannot convert value of type UnsafeMutablePointer<Int32> to type 'UnsafeMutablePointer'(aka UnsafeMutablePointer<()>) in coercion

Any idea?


Solution

  • Could this help:

    startIdx = unsafeBitCast(realloc(startIdx, sizeof(Int32) * newBitsLength), UnsafeMutablePointer<Int32>.self)