Swift 将字符串转换为 UnsafeMutablePointer<Int8>

标签 swift pointers xcode6

我有一个映射到 Swift 的 C 函数定义为:

func swe_set_eph_path(path: UnsafeMutablePointer<Int8>) -> Void

我正在尝试将路径传递给该函数并尝试过:

        var path = [Int8](count: 1024, repeatedValue: 0);
        for i in 0...NSBundle.mainBundle().bundlePath.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)-1
        {
            var range = i..<i+1
            path[i] = String.toInt(NSBundle.mainBundle().bundlePath[range])
        }
        println("\(path)")
        swe_set_ephe_path(&path)

但是在 path[i] 行我得到了错误:

'subscript' is unavailable: cannot subscript String with a range of Int

swe_set_ephe_path(NSBundle.mainBundle().bundlePath)

也不

swe_set_ephe_path(&NSBundle.mainBundle().bundlePath)

也不行

除了不起作用之外,我觉得必须有一种更好、更简单的方法来做到这一点。以前使用 CString 的 StackOverflow 答案似乎不再有效。有什么建议吗?

最佳答案

Previous answers on StackOverflow using CString don't seem to work anymore

尽管如此,UnsafePointer<Int8>是 C 字符串。如果您的上下文绝对需要 UnsafeMutablePointer , 只是强制, 像这样:

let s = NSBundle.mainBundle().bundlePath
let cs = (s as NSString).UTF8String
var buffer = UnsafeMutablePointer<Int8>(cs)
swe_set_ephe_path(buffer)

当然我没有你的swe_set_ephe_path ,但是当它像这样 stub 时,它在我的测试中工作正常:

func swe_set_ephe_path(path: UnsafeMutablePointer<Int8>) {
    println(String.fromCString(path))
}

关于Swift 将字符串转换为 UnsafeMutablePointer<Int8>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30042494/

相关文章:

ios - Swift 无法使用常规方法将 Int 转换为 String

ios - 符合协议(protocol)的元素集合 ? : Viewer Swift

ios - Objective C 的 Swift 语法

c++ - 我可以直接从 C++ 中的 vector 元素指针获取索引吗?

macos - Swift:如何单击按钮打开一个新窗口?

ios - 在Xcode 6.1上构建应用时出错?

ios - 如何在没有导航 Controller 的情况下从第三个 ViewController 弹出到初始 ViewController?

swift - 如何使用 "OR"在 Swift 中比较字符串

C指针错误值?

C 结构和指针程序在编译时什么都不做。不显示错误或警告