Swift 中的 Realloc UnsafeMutablePointer 导致错误

Realloc UnsafeMutablePointer in Swift cause error

我正在将一些关于 C 指针的操作转换为 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
    }
}

我知道了

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

有什么想法吗?

这有帮助吗:

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