gpt4 book ai didi

ios - 无法在 iOS Swift 中获取 SecKey UnsafeMutablePointer

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:22 34 4
gpt4 key购买 nike

我在swift中做一个涉及RSA加密的项目,遇到一个指针问题如下:

我有一个全局 var publicKey: SecKey?可选值,我需要获取 UnsafeMutablePointer<Unmanaged<SecKey>?>指向它的指针,即 SecKeyGeneratePair 中所需的数据类型功能。

我试图将指针定义为:

var keyPointer = UnsafeMutablePointer<Unmanaged<SecKey>?>(publicKey!)

但是编译器提示Cannot invoke 'init' with an argument of type @lvalue SecKey错误

根据 Using Swift with Cocoa and Objective-C 一书,在 Core FoundationUnmanaged Objects 部分,它指出Unmanaged<T>结构提供了2个方法takeUnretainedValue()takeRetainedValue() .但尝试实现它们时,会出现以下错误

var keyPointer = UnsafeMutablePointer<Unmanaged<SecKey>?>(publicKey!.takeRetainedValue())

“SecKey”没有名为“takeRetainedValue”的成员

任何解决此问题的帮助将不胜感激

最佳答案

试试这个:

var publicKey: SecKey?
var privateKey: SecKey?

var publicKeyUnManaged:Unmanaged<SecKey>?
var privateKeyUnManaged:Unmanaged<SecKey>?
let dic:[String:String] = [kSecAttrKeyType:kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits:"2048"]
SecKeyGeneratePair(dic, &publicKeyUnManaged, &privateKeyUnManaged)

publicKey = publicKeyUnManaged?.takeRetainedValue()
privateKey = privateKeyUnManaged?.takeRetainedValue()

您不必创建 UnsafeMutablePointer<Unmanaged<SecKey>?>手动。如 this document 中所述,

When a function is declared as taking an UnsafeMutablePointer argument, it can accept any of the following:

  • nil, which is passed as a null pointer
  • An UnsafeMutablePointer value
  • An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
  • An in-out [Type] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call

在这种情况下,我们可以使用第三个“in-out”表达式。

关于ios - 无法在 iOS Swift 中获取 SecKey UnsafeMutablePointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26812690/

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