gpt4 book ai didi

Swift 将字符串转换为 UnsafeMutablePointer

转载 作者:IT王子 更新时间:2023-10-29 05:24:41 24 4
gpt4 key购买 nike

我有一个映射到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com