How to convert array to UnsafeMutablePointer<Un

2019-04-28 18:18发布

Here was my workable code in the previous version of Swift:

 let imageOptionsDictKeys = [ kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey,  kCVPixelBufferHeightKey, kCVPixelBufferOpenGLESCompatibilityKey, kCVPixelBufferIOSurfacePropertiesKey]
 let imageOptionsDictValues = [ cvPixelFormatType,  frameW, frameH, boolYES]

 var keyCallbacks = kCFTypeDictionaryKeyCallBacks
 var valueCallbacks = kCFTypeDictionaryValueCallBacks

 let imageOptions = CFDictionaryCreate(kCFAllocatorDefault, UnsafeMutablePointer(imageOptionsDictKeys), UnsafeMutablePointer(imageOptionsDictValues), 4, &keyCallbacks, &valueCallbacks)

After changes in the Swift 3.0 I have to convert my keys and values arrays into UnsafeMutablePointer<UnsafeRawPointer?> for creating CFDictionary.

This way:

    let imageOptionsDictKeysPointer =  UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
    imageOptionsDictKeysPointer.initialize(to: imageOptionsDictKeys)

gives an Bad Access error.

And after reading documentation I am trying to compile this code:

        let imageOptionsDictKeys = [kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey,  kCVPixelBufferHeightKey, kCVPixelBufferOpenGLESCompatibilityKey]
        let imageOptionsDictKeysRawPointer = Unmanaged.passUnretained(imageOptionsDictKeys).toOpaque()
        let imageOptionsDictKeysPointer =  UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
        imageOptionsDictKeysPointer.initialize(to: imageOptionsDictKeysRawPointer)

        let imageOptionsDictValues = [ cvPixelFormatType,  frameW, frameH, boolYES]
        let imageOptionsDictValuesRawPointer = Unmanaged.passUnretained(imageOptionsDictValues).toOpaque()
        let imageOptionsDictValuesPointer =  UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
        imageOptionsDictValuesPointer.initialize(to: imageOptionsDictValuesRawPointer)

        let imageOptions = CFDictionaryCreate(kCFAllocatorDefault, imageOptionsDictKeysPointer, imageOptionsDictValuesPointer, 4, &keyCallbacks, &valueCallbacks)

but error Generic parameter 'Instance' could not be inferred appears in the lines Unmanaged.passUnretained(array).toOpaque()

I have no idea how to create CFDictionary programmatically now.

1条回答
贼婆χ
2楼-- · 2019-04-28 19:16

I just solved a similar issue converting arrays to UnsafeMutablePointer< UnsafeMutablePointer<T>> which you can find here: Swift 3 UnsafeMutablePointer initialization for C type float**

To convert swift arrays using the same scheme, use UnsafeMuTablePointer as suggested here: http://technology.meronapps.com/2016/09/27/swift-3-0-unsafe-world-2/

查看更多
登录 后发表回答