gpt4 book ai didi

c - 如何正确处理 UnsafeMutablePointer

转载 作者:IT王子 更新时间:2023-10-28 23:38:27 26 4
gpt4 key购买 nike

我有点困惑。我什么时候必须调用 free 以及何时销毁/dealloc?我正在编写一个简短的代码片段来学习核心音频。我想如果我调用 UnsafeMutablePointer<Type>.alloc(size)那么我应该调用destroy & dealloc .但是如果我使用 malloc()calloc()我应该调用free() .

在 Learning Core Audio 的这个例子中,下面的代码片段让我想知道:

var asbds = UnsafeMutablePointer<AudioStreamBasicDescription>.alloc(Int(infoSize))
audioErr = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
UInt32(sizeof(fileTypeAndFormat.dynamicType)), &fileTypeAndFormat,
&infoSize, asbds)

这里我使用 alloc .释放内存 free被调用。

free(asbds)

但为什么不

asbds.destroy(Int(infoSize))
asbds.dealloc(Int(infoSize))

我希望遵守规则。

我会很感激任何帮助,因为这让我头晕目眩。文档说我负责销毁和解除分配,以便清楚该部分,但是以哪种方式?

最佳答案

UnsafeMutablePointer Structure Reference .

The pointer can be in one of the following states:

  • Memory is not allocated (for example, pointer is null, or memory has been deallocated previously).

  • Memory is allocated, but value has not been initialized.

  • Memory is allocated and value is initialized.

您可以在“分配和初始化”时安全地使用指向区域。所以,要想正确使用Swift的UnsafeMutablePointer,需要2步使用前,2步使用后。

(1) 分配:alloc(_:).

(2) 初始化:初始化...()

您可以在这里安全地使用分配和初始化的区域。

(3) 取消初始化:destroy(_:)

(4) 解除分配:dealloc(_:)


以及为什么你可以将 free() 用于 alloc(_:) 的内存,那是因为 Swift 使用 malloc(_:)alloc(_:) 的当前实现中。因此,使用 free 意味着您的应用程序依赖于 Swift 运行时的当前实现。


所以,使用 UnsafeMutablePointer 有点困难和烦人。您应该考虑将数组作为指针传递。在你的情况下,你可以这样写:

    let elementCount = Int(infoSize) / strideof(AudioStreamBasicDescription)
var asbds: [AudioStreamBasicDescription] = Array(count: elementCount, repeatedValue: AudioStreamBasicDescription())
audioErr = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
UInt32(sizeof(fileTypeAndFormat.dynamicType)), &fileTypeAndFormat,
&infoSize, &asbds)

(我认为即使在使用 UnsafeMutablePointer 时你也应该使用这个 elementCountalloc(_:)dealloc(_: ) 使用“元素数量”,而不是“字节大小”。)

关于c - 如何正确处理 UnsafeMutablePointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com