正确使用 NSGetExecutablePath

Properly used NSGetExecutablePath

我尝试在运行时获取我的应用程序的路径。我从 C 中找到了一些旧源并将其相应地转换为函数参数类型定义:

var path = [Int8] (count:1024, repeatedValue: 0)
var bufsize : UInt32 = 1024

if _NSGetExecutablePath(&path, &bufsize) == 0 {
println("executable path is \(path)")
}

它可以运行,但我需要一个 Int8 数组,而不是字符串。所以我必须搜索字符链的末尾并将其转换回字符串。在 SWIFT 中使用此功能的正确方法是什么?

您需要从 C 字符串

创建一个Swift字符串
let executablePath = String(CString: path, encoding: NSASCIIStringEncoding)!
println("executable path is \(executablePath)")

但是有一种更简单的方法来获取可执行文件的路径

let executablePath = Bundle.main.executablePath!

在Swift 4

let executablePath = Bundle.main.executablePath!
print(executablePath)