快速将字符串转换为UnsafeMutablePointer< Int8> [英] Swift convert string to UnsafeMutablePointer<Int8>

查看:270
本文介绍了快速将字符串转换为UnsafeMutablePointer< Int8>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a C function mapped to Swift defined as:

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

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

I am trying to pass a path to the function and have tried:

        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]行上,我得到了错误:

but on the path[i] line I get the error:

下标"不可用:无法下标范围为的字符串 诠释

'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上的答案似乎不再起作用.有什么建议吗?

Besides not working, I feel there has got to be a better, less convoluted way of doing this. Previous answers on StackOverflow using CString don't seem to work anymore. Any suggestions?

推荐答案

使用CString在StackOverflow上的先前答案似乎不再起作用

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

尽管如此,UnsafePointer<Int8>是一个C字符串.如果您的上下文绝对需要UnsafeMutablePointer,请像这样强制使用

Nevertheless, UnsafePointer<Int8> is a C string. If your context absolutely requires an UnsafeMutablePointer, just coerce, like this:

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,但是当它像这样被存根时,它在我的测试中效果很好:

Of course I don't have your swe_set_ephe_path, but it works fine in my testing when it is stubbed like this:

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

这篇关于快速将字符串转换为UnsafeMutablePointer&lt; Int8&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆