How to handle UnsafeMutablePointer correctly

冷暖自知 提交于 2019-12-01 04:11:54

See the 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.

You can use the pointed region safely when "allocated and initialized". So, if you want to use Swift's UnsafeMutablePointer correctly, you need 2 steps before using and 2 steps after using.

(1) Allocate: alloc(_:).

(2) Initilize: initialize...()

You can safely use the allocated and initialized region here.

(3) Deinitialize: destroy(_:)

(4) Deallocate: dealloc(_:)


And why you can use free() for alloc(_:)ed memory, that's because Swift uses malloc(_:) in the current implementation of alloc(_:). So, using free means that your app depends on the current implementation of the Swift runtime.


So, using UnsafeMutablePointer is sort of difficult and annoying. You should consider passing an array as a pointer. In your case, you can write something like this:

    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)

(I think you should use this elementCount even when using UnsafeMutablePointer. alloc(_:) or dealloc(_:) uses "number of elements", not "byte size".)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!