如何从CMutablePointer获取值?

时间:2014-06-06 09:24:41

标签: swift core-foundation

我正在尝试使用一些C基础API,比如Swift语言中的Launch Services,但我对如何正确使用CMutablePointer有点误解。我有以下代码:

var itemInfo: CMutablePointer<LSItemInfoRecord> = nil
var path: CFStringRef = "/test.txt"
var isFile: Boolean = 0

let url = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, isFile)
let status: OSStatus = LSCopyItemInfoForURL(url, kLSRequestAllFlags, itemInfo)

它编译得很好,但如何作为Swift CMutablePointer<LSItemInfoRecord>结构类型访问LSItemInfoRecord值?也许我只是错过了,但我不知道在documentation中解释了这一点。

我还尝试了以下代码,使用&前缀,建议here

var itemInfo: LSItemInfoRecord? = nil
var path: CFStringRef = "/test.txt"
var isFile: Boolean = 0

let url = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, isFile)
let status: OSStatus = LSCopyItemInfoForURL(url, kLSRequestAllFlags, &itemInfo)

但是我收到以下错误:Cannot convert the expression type 'OSStatus' to type 'inout LSItemInfoRecord?'

我还尝试使用非可选(var itemInfo: LSItemInfoRecord),但编译器声称itemInfo未初始化,这显然是必需的行为。

那么,我怎么能跑这个呢?

1 个答案:

答案 0 :(得分:1)

您必须初始化结构:

var itemInfo = LSItemInfoRecord(flags: 0, filetype: 0, creator: 0, `extension`: nil)

...

let status: OSStatus = LSCopyItemInfoForURL(url, kLSRequestAllFlags, &itemInfo)

请注意extension必须转义,因为它是Swift中的关键字。

修改

一个完整的例子:

var itemInfo = LSItemInfoRecord(flags: 0, filetype: 0, creator: 0, `extension`: nil)

var path: CFStringRef = "/Applications/Safari.app"
var isFile: Boolean = 0

let url = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, isFile)

let status: OSStatus = LSCopyItemInfoForURL(url, kLSRequestAllInfo, &itemInfo)

let statusString: String = SecCopyErrorMessageString(status, nil).takeUnretainedValue()

println("Status: \(status), \"\(statusString)\"")
println("Creator: \(itemInfo.creator)")
println("Flags: \(itemInfo.flags)")

打印

Status: 0, "No error."
Creator: 1936093801
Flags: 271599758