如何通过 `UnsafeMutablePointer<CFTypeRef?>?` 参数 return 字典?

How to return a dictionary through a `UnsafeMutablePointer<CFTypeRef?>?` parameter?

为了测试,我创建了一个模拟 class,它包装了 Security 框架函数。一切正常,除了 我试图伪造 SecItemCopyMatching(_:_:)。完整的签名是:

func SecItemCopyMatching(_ query: CFDictionary, _ result: UnsafeMutablePointer<CFTypeRef?>?) -> OSStatus

我不想使用 Security 框架的 SecItemCopyMatching(_:_:) 实现一个具有相同签名的虚拟机 供自己测试。

以下代码段来自 the official documentation,介绍如何处理函数结果。我不知道如何通过 UnsafeMutablePointer 以相同的方式使用虚拟字典。我无法为指针分配任何内容,并且被 UnsafeMutablePointer<CFTypeRef?>? 弄糊涂了 - 这是一个指向指针的指针吗?

guard let existingItem = item as? [String : Any],
    let passwordData = existingItem[kSecValueData as String] as? Data,
    let password = String(data: passwordData, encoding: String.Encoding.utf8),
    let username = existingItem[kSecAttrAccount as String] as? String
    else {
        throw KeychainError.unexpectedPasswordData
}

我找到的有效解决方案:

func SecItemCopyMatching(_ query: CFDictionary, _ result: UnsafeMutablePointer<CFTypeRef?>?) -> OSStatus {
    let item: [String: Any] = [
        kSecAttrAccount as String: "username",
        kSecValueData as String: "password".data(using: String.Encoding.utf8)!
    ]

    result?.pointee = item as AnyObject
    return copyMatchingStatus
}

他们要理解的关键信息:CFTypeRef 直接映射到 AnyObject(参见 Working with Core Foundation Types)。将字典转换为 AnyObject 可以将赋值作为指针对象。