加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift将字符串转换为UnsafeMutablePointer

发布时间:2020-12-14 05:20:20 所属栏目:百科 来源:网络整理
导读:我有一个C函数映射到 Swift定义为: func swe_set_eph_path(path: UnsafeMutablePointerInt8) - Void 我试图通过一个路径的功能,并尝试: var path = [Int8](count: 1024,repeatedValue: 0); for i in 0...NSBundle.mainBundle().bundlePath.lengthOfBytesUs
我有一个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))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读