Swift:UnsafeMutablePointer.deallocate(capacity:) 与 free() 的互操作性

Swift: Interoperability of UnsafeMutablePointer.deallocate(capacity:) with free()

我可以将 UnsafeMutablePointer.deallocate(capacity:) 与之前使用 malloc 分配内存的指针一起使用吗?即,deallocate 是否表现得像 free

发生这种情况的一种情况是从 Swift 调用 C 函数时使用 malloc 分配内存并期望调用者稍后 free() 该内存。例如 LIBMTP_Detect_Raw_Devices 函数 (see here for an example use)。该函数期望调用者释放函数内部分配的内存 (rawdevices)。

文档对此不明确,但测试表明互操作性。

在 C 中使用 malloc(),然后在 Swift 中调用 deallocate() 并尝试 free() C 中的指针(反之亦然)将导致 run-time 错误,但如果只使用 deallocate()free() 之一,而不是同时使用两者,代码将 运行 正常。

类似地,在 Swift 中分配结构,然后在 Swift 中使用 deallocate() 并在 C 中使用 free()(或相反)也会导致run-time 错误。

也可以按照@jtbandes 的建议在Swift 中使用free()。事实上,这种方法可能比调用 deallocate().

更安全

关于文档,请参阅 https://developer.apple.com/reference/swift/unsafemutablepointer

此外,您可以在此处挖掘 UnsafeMutablePointer 的源代码:https://github.com/apple/swift/blob/master/stdlib/public/core/UnsafePointer.swift.gyb

我还没来得及搞清楚实现。