你如何在Swift中使用SecKeychainGetPath

时间:2015-02-19 18:23:38

标签: swift

我正在尝试在Swift中调用OS X安全方法SecKeychainGetPath。这就是我到目前为止所做的:

var pLength = 1024 as UInt32
var pName = malloc(1024)
let oStatus = SecKeychainGetPath(chain, &pLength, &pName)

SecKeychainGetPath的方法定义是:

func SecKeychainGetPath(keychain: SecKeychain!, ioPathLength: UnsafeMutablePointer<UInt32>, pathName: UnsafeMutablePointer<Int8>) -> OSStatus

我得到的错误是:

Cannot invoke 'SecKeychainGetPath' with an argument list of type '(SecKeychain, inout UInt32, inout UnsafeMutablePointer<Void>)'

我相信我的chain参数很好,但我认为这是编译器抱怨的pName参数。 malloc会返回UnsafeMutablePointer<Void>,其中SecKeychainGetPath期望pNameUnsafeMutablePointer<Int8>。我尝试过铸造,但标记为不安全且不相关。

1 个答案:

答案 0 :(得分:4)

您可以将任何指针传递给期望UnsafeMutablePointer<Void>的函数,但是当需要该类型时,您需要传递匹配的指针。在这种情况下,您需要UnsafeMutablePointer<Int8>

var pLength = 1024 as UInt32
var pName = UnsafeMutablePointer<Int8>.alloc(1024)
let oStatus = SecKeychainGetPath(chain, &pLength, pName)

另请注意,UnsafeMutablePointer实例在函数调用中不需要&前缀。

或者,您可以构建一个数组而不是UnsafeMutablePointer,并将其作为inout参数传递:

var pName = Array(count: 1024, repeatedValue: 0 as Int8)
var pLength = UInt32(pName.count)
let oStatus = SecKeychainGetPath(chain, &pLength, &pName)

这种替代方法的好处是Swift正在为您处理所有内存管理 - 稍后不需要dealloc指针。