iOS:在swift中将UnsafeMutablePointer <int8>转换为String?

时间:2015-11-28 18:12:24

标签: ios swift

正如标题所说,在swift中将UnsafeMutablePointer转换为String的正确方法是什么?

//lets say x = UnsafeMutablePointer<Int8> 

var str = x.memory.????

我尝试使用x.memory.description显然这是错误的,给我一个错误的字符串值。

3 个答案:

答案 0 :(得分:25)

如果指针指向以NUL结尾的UTF-8字节的C字符串,则可以执行以下操作:

import Foundation

let x: UnsafeMutablePointer<Int8> = ...
// or UnsafePointer<Int8>
// or UnsafePointer<UInt8>
// or UnsafeMutablePointer<UInt8>

let str = String(cString: x)

答案 1 :(得分:7)

时代变了。在 Swift 3 + 中你会这样做:

如果您想要验证utf-8:

let str: String? = String(validatingUTF8: c_str)

如果要将utf-8错误转换为unicode错误符号:�

let str: String = String(cString: c_str)

假设c_str类型为UnsafePointer<UInt8>UnsafePointer<CChar>,且类型相同且大多数C函数都返回。

答案 2 :(得分:1)

这样:

let str: String? = String(validatingUTF8: c_str)

似乎不适用于UnsafeMutablePointer&lt; UInt8&gt; (这似乎是我的数据)。

这是我轻而易举地解决如何做C / Perl系统功能的事情:

let task = Process()
task.launchPath = "/bin/ls"
task.arguments = ["-lh"]

let pipe = Pipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
var unsafePointer = UnsafeMutablePointer<Int8>.allocate(capacity: data.count)
data.copyBytes(to: unsafePointer, count: data.count)

let output : String = String(cString: unsafePointer)
print(output)
//let output : String? = String(validatingUTF8: unsafePointer)
//print(output!)

如果我切换到validatingUTF8(可选)而不是cString,我会收到此错误:

./ls.swift:19:37: error: cannot convert value of type 'UnsafeMutablePointer<UInt8>' to expected argument type 'UnsafePointer<CChar>' (aka 'UnsafePointer<Int8>')
let output : String? = String(validatingUTF8: unsafePointer)
                                    ^~~~~~~~~~~~~

关于如何在管道输出上验证UTF8的想法(所以我没有在任何地方获得unicode错误符号)?

(是的,我没有正确检查我的打印选项(),这不是我正在解决的问题;-))。