Swift 中的 Realloc UnsafeMutablePointer 导致错误
Posted
技术标签:
【中文标题】Swift 中的 Realloc UnsafeMutablePointer 导致错误【英文标题】:Realloc UnsafeMutablePointer in Swift cause error 【发布时间】:2016-04-13 02:15:33 【问题描述】:我正在将一些关于 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
我知道了
无法将
UnsafeMutablePointer<Int32>
类型的值强制转换为类型“UnsafeMutablePointer”(又名UnsafeMutablePointer<()>
)
有什么想法吗?
【问题讨论】:
【参考方案1】:这能帮上忙吗:
startIdx = unsafeBitCast(realloc(startIdx, sizeof(Int32) * newBitsLength), UnsafeMutablePointer<Int32>.self)
【讨论】:
以上是关于Swift 中的 Realloc UnsafeMutablePointer 导致错误的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 3.1 中,不推荐使用 UnsafeMutablePointer.initialize(from:)
找出分配的内存是不是被 C 中的 realloc() 函数释放