我有一个C函数映射到
Swift定义为:
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)
但是在路径[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,但是当我的测试当它被这样的stubbed它工作正常:
func swe_set_ephe_path(path: UnsafeMutablePointer<Int8>) { println(String.fromCString(path)) }